【问题标题】:Binding ItemsSource to an EntityFramework ObjectSet<T> does not generate content将 ItemsSource 绑定到 EntityFramework ObjectSet<T> 不会生成内容
【发布时间】:2012-01-03 09:08:58
【问题描述】:

我们的应用程序正在使用 XAML 中的多个 TreeViewItem 和 DataGrid 控件,它们的ItemsSource 属性绑定到实体框架ObjectSet&lt;Entity&gt; 集合。问题在于 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


【解决方案1】:

我的猜测是:在 IEnumerable 的情况下,您将表达式传递给 ItemsSource,而不是 SOURCE。当你调用:ToArray() 时,它会执行表达式并返回 ItemsSource 的实际数据。

总结第一种情况:你告诉WPF如何获取ItemsSource。第二种情况:你传递实际的数据源。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    相关资源
    最近更新 更多