Why are DataContext and ItemsSource not redundant?

烂漫一生 提交于 2019-11-28 17:13:29
Kent Boogaart

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!