In WPF Databinding, I understand that you have DataContext
which tells an element what data it is going to bind to and ItemsSourc
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.
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.