考虑以下模型...
数据模型
我有一个 WCF 数据服务 (PMService),它将数据模型公开给我的 JobsViewModel
WCF 数据服务
namespace PM.DataService
{
[ServiceContract]
public class PMService
{
[OperationContract]
public ObservableCollection<Job> GetAllJobs()
{
using (var context = new logisticDBEntities())
{
var result = context.Jobs.ToList();
result.ForEach(e => context.Detach(e));
return new ObservableCollection<Job>(result);
}
}
[OperationContract]
public ObservableCollection<Status> GetStatuses()
{
using (var context = new logisticDBEntities())
{
var result = context.Statuses.ToList();
result.ForEach(e => context.Detach(e));
return new ObservableCollection<Status>(result);
}
}
}
}
工作视图模型
namespace PM.UI.ViewModel
{
public class JobsViewModel:INotifyPropertyChanged
{
private PMServiceClient serviceClient = new PMServiceClient();
public JobsViewModel()
{
this.RefreshAllJobs();
}
private void RefreshAllJobs()
{
this.serviceClient.GetAllJobsCompleted += (s, e) =>
{
this.AllJobs = e.Result;
};
this.serviceClient.GetAllJobsAsync();
}
private ObservableCollection<Job> allJobs;
public ObservableCollection<Job> AllJobs
{
get{
return this.allJobs;
}
set
{
this.allJobs = value;
OnPropertyChanged("AllJobs");
}
}
private ObservableCollection<Status> statuses;
public ObservableCollection<Status> Statuses
{
get
{
return this.statuses;
}
set
{
this.statuses = value;
this.OnPropertyChanged("Statuses");
}
}
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
我在 MainWindow.xaml 中包含了我的视图模型
主窗口.xaml
<Window x:Class="PM.FullClient.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:PM.UI"
xmlns:vms="clr-namespace:PM.UI.ViewModel"
Title="MainWindow" Height="475" Width="575">
<Window.DataContext>
<vms:JobsViewModel/>
</Window.DataContext>
使用 DataGrid 我已成功显示所有作业。
<DataGrid AutoGenerateColumns="False"
ItemsSource="{Binding Path=AllJobs}" Margin="6">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=jobNo}" Header="Job #" />
<DataGridTextColumn Binding="{Binding Path=jobStatus}" Header="Status" />
<DataGridTextColumn Binding="{Binding Path=jobDate}" Header="Date" />
<DataGridTextColumn Binding="{Binding Path=Statuses}" Header="Status" />
</DataGrid.Columns>
</DataGrid>
JobsDataGrid_output
在 JobsDataGrid 中,您可以看到我有状态的ID。
现在状态和工作有一对多的关系;Job 将持有 Status 的主键。
我想要做的是显示jobStatus(statusId)的相应statusCaption。
按照 Ucodia 的建议进行编辑
我在下面插入了代码
...
var result = context.Jobs.ToList();
result.ForEach(e => context.LoadProperty(e, "Status"));
result.ForEach(e => context.Detach(e));
...
结果还是一样(状态栏还是空白
我在调试模式下运行应用程序并得到以下信息......希望它能帮助有人解释我做错了什么。
>>>调试数据截图