【发布时间】:2012-01-03 09:08:58
【问题描述】:
我们的应用程序正在使用 XAML 中的多个 TreeViewItem 和 DataGrid 控件,它们的ItemsSource 属性绑定到实体框架ObjectSet<Entity> 集合。问题在于 UI 控件的行为就像 ObjectSet 为空一样。
EF ObjectContext 包含在静态类的单例类中:
public static class BusinessData
{
public static readonly BizDataSource Source = BizDataSource.Instance;
}
public class BizDataSource : INotifyPropertyChanged
{
private BusinessEntitiesObjectContext _context = ...;
ObjectSets 是从单例中的只读属性返回的:
public IEnumerable<Employee> RetiredEmployees
{
get {
return (from it in _context.Employees where it.Status == "Retired" select it);
}
}
最后,ItemsSource 是绑定到集合的数据,当知道数据源已更新时,INotifyPropertyChanged 用于更新 UI:
<TreeViewItem x:Name="PART_TVI" Header="Retired Employees"
ItemsSource="{Binding
Source={x:Static local:BusinessData.Source},
Path=RetiredEmployees}"
/>
调试步骤显示绑定正确地提供了一个解析为业务对象的 IEnumerable,但似乎控件没有对其进行迭代。例如,如果我将此代码添加到窗口中:
PART_TVI.ItemsSource = BusinessData.Source.RetiredEmployees;
发生与 XAML 绑定相同的行为:无。然而:
PART_TVI.ItemsSource = BusinessData.Source.RetiredEmployees.ToArray();
啊哈!现在,我们已经在 TreeViewItem 中生成了内容。但是,为什么这首先是必要的?
【问题讨论】:
-
它是一种 linq 行为。 ToArray 立即运行您的查询,因此您可以看到您的内容
-
您是否尝试将
.ToArray()或.ToList()添加到get 语句中?
标签: c# wpf entity-framework data-binding