【问题标题】:Why are DataContext and ItemsSource not redundant?为什么 DataContext 和 ItemsSource 不是多余的?
【发布时间】:2010-10-22 01:20:42
【问题描述】:

在 WPF 数据绑定中,我知道您有 DataContext 告诉元素它将绑定到哪些数据,而 ItemsSource 则“执行绑定”。

但是例如在这个简单的示例中,ItemsSource 似乎没有做任何有用的事情,因为 除了 bind 之外,您还希望元素对 DataContext 做什么其他事情 em> 给它?

<ListBox DataContext="{StaticResource customers}" 
         ItemsSource="{Binding}">

ItemsSource 的更复杂示例中,您的路径和来源似乎正在侵占 DataContext 的领域。

ItemsSource="{Binding Path=TheImages, Source={StaticResource ImageFactoryDS}}"

理解这两个概念以了解何时以及如何在各种编码场景中应用它们的最佳方式是什么?

【问题讨论】:

    标签: wpf data-binding datacontext itemssource


    【解决方案1】:

    DataContext 只是在未指定显式源的情况下为绑定获取上下文的便捷方式。它是继承的,因此可以这样做:

    <StackPanel DataContext="{StaticResource Data}">
        <ListBox ItemsSource="{Binding Customers}"/>
        <ListBox ItemsSource="{Binding Orders}"/>
    </StackPanel>
    

    这里,CustomersOrders 是名为“数据”的资源上的集合。在你的情况下,你可以这样做:

    <ListBox ItemsSource="{Binding Source={StaticResource customers}}"/>
    

    因为没有其他控件需要上下文集。

    【讨论】:

    • 谢谢,您回答的第二部分是我在 DataContext 和 Source 之间缺少的链接。所以你可以这样想:(其实我想知道为什么WPF不只使用那个语法)
    • @Edward:也许,但还有其他类型的来源,例如RelativeSource 和ElementName。查看 Binding 类的 API 文档。
    【解决方案2】:

    ItemsSource 属性将直接与集合对象或 DataContext 属性的绑定对象的集合属性绑定。

    经验:

    Class Root
    {
       public string Name;
       public List<ChildRoot> childRoots = new List<ChildRoot>();
    }
    
    Class ChildRoot
    {
       public string childName;
    }
    

    将有两种方式绑定ListBox控件:

    1) 与 DataContext 绑定:

        Root r = new Root()
        r.Name = "ROOT1";
    
        ChildRoot c1 = new ChildRoot()
        c1.childName = "Child1";
        r.childRoots.Add(c1);
    
        c1 = new ChildRoot()
        c1.childName = "Child2";
        r.childRoots.Add(c1);
    
        c1 = new ChildRoot()
        c1.childName = "Child3";
        r.childRoots.Add(c1);
    
    treeView.DataContext = r;
    
    <TreeViewItem ItemsSource="{Binding Path=childRoots}" Header="{Binding Path=Name}">
    <HierarchicalDataTemplate DataType="{x:Type local:Root}" ItemsSource="{Binding Path=childRoots}">
    

    2) 与 ItemSource 绑定:

    ItemsSource 属性总是需要收集。 这里我们要绑定 Root 的集合

    List<Root> lstRoots = new List<Root>();
    lstRoots.Add(r);
    
    <HierarchicalDataTemplate DataType="{x:Type local:Root}" ItemsSource="{Binding Path=childRoots}">
    

    在第一个示例中,我们绑定了 DataContext,该对象内部有对象,我们有与 ItemSource 属性绑定的集合,而在第二个示例中,我们直接将 ItemSource 属性与集合对象绑定。

    【讨论】:

      猜你喜欢
      • 2011-03-03
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 2011-01-07
      相关资源
      最近更新 更多