Why are DataContext and ItemsSource not redundant?

后端 未结 2 1479
灰色年华
灰色年华 2020-12-13 04:15

In WPF Databinding, I understand that you have DataContext which tells an element what data it is going to bind to and ItemsSourc

相关标签:
2条回答
  • 2020-12-13 04:33

    ItemsSource property will be binded with collection object directly OR collection property of binding object of DataContext property.

    Exp:

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

    There will be two ways to bind ListBox control:

    1) Binding with 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) Binding with ItemSource:

    ItemsSource property takes collection always. here we have to bind collection of Root

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

    In First example we have bind DataContext which has object inside that object we have collection which we binded with ItemSource property where in Second example we have directly bind ItemSource property with collection object.

    0 讨论(0)
  • 2020-12-13 04:47

    DataContext is just a handy way to pick up a context for bindings for the cases where an explicit source isn't specified. It is inherited, which makes it possible to do this:

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

    Here, Customers and Orders are collections on the resource called "Data". In your case, you could have just done this:

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

    since no other control needed the context set.

    0 讨论(0)
提交回复
热议问题