在 WPF 数据绑定(bind)中,我知道您有 DataContext
它告诉元素它将绑定(bind)到什么数据和 ItemsSource
哪个“进行绑定(bind)”。
但是例如在这个简单的例子中, ItemsSource
正在做任何有用的事情,您还希望元素对 DataContext
做什么?除了绑定(bind)到它 ?
<ListBox DataContext="{StaticResource customers}"
ItemsSource="{Binding}">
在更复杂的 示例中
ItemsSource
,您的路径和源头似乎正在侵占 的领土DataContext
.ItemsSource="{Binding Path=TheImages, Source={StaticResource ImageFactoryDS}}"
理解这两个概念以了解何时以及如何在各种编码场景中应用它们的最佳方法是什么?
最佳答案
ItemsSource 属性将直接与集合对象或 DataContext 属性的绑定(bind)对象的集合属性绑定(bind)。
经验:
Class Root
{
public string Name;
public List<ChildRoot> childRoots = new List<ChildRoot>();
}
Class ChildRoot
{
public string childName;
}
将有两种方式绑定(bind) ListBox 控件:
1)与DataContext绑定(bind):
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 绑定(bind):
ItemsSource 属性总是需要收集。
在这里我们必须绑定(bind) Root 的集合
List<Root> lstRoots = new List<Root>();
lstRoots.Add(r);
<HierarchicalDataTemplate DataType="{x:Type local:Root}" ItemsSource="{Binding Path=childRoots}">
在第一个示例中,我们绑定(bind)了 DataContext,该对象内部有对象,我们有与 ItemSource 属性绑定(bind)的集合,而在第二个示例中,我们直接将 ItemSource 属性与集合对象绑定(bind)。
关于wpf - 为什么 DataContext 和 ItemsSource 不是多余的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/793340/