wpf /数据绑定如何解决这种歧义?

时间:2012-12-05 14:35:01

标签: wpf data-binding

<StackPanel DataContext="{StaticResource Employees1}">
    <ListBox ItemsSource="{Binding}" DisplayMemberPath="Name" 
                  IsSynchronizedWithCurrentItem="True"/>
    <Label Content="{Binding Path=Count}"/>
    <Label Content="{Binding Path=Name}"/>
</StackPanel>

如何解决标签的绑定问题?如何确定第二个标签的内容绑定到Employees1.Count(而不是Employee.Count),而第一个标签绑定到 Employee.Name并与列表框选择同步?另外,如果我想将第一个标签绑定到Employee.Count呢?

(Employee具有属性Name(可能还有Count),Employees1是Employee类型的ObservableCollection)。


编辑:所以,这里的问题是为什么第一个标签显示ObservableCollection中的员工数量,而第二个标签显示特定员工的名称集合,当前在ListBox中选择的集合。显然,第一个标签绑定到整个集合,第二个标签绑定到集合中的特定员工。但为什么,以及如何控制这种行为。

3 个答案:

答案 0 :(得分:1)

从MSDN Data Binding Overview, Binding To Collections,“当前项指针”部分:

  

因为WPF仅使用视图(视图)绑定到集合   你指定,或集合的默认视图),所有绑定   集合有一个当前项目指针。

和“Master-Detail Binding Scenario”部分:

  

这是有效的,因为当一个单例对象(ContentControl在此   case)绑定到一个集合视图,它会自动绑定到   视图的CurrentItem。

在您的示例中,第二个Label 自动绑定到Employees1集合的默认视图的当前项。第一个Label也会像这样绑定,但由于item对象没有Count属性,它显然会回退到对集合本身的Count属性的绑定。但是我不知道后面的行为是否记录在某处。

答案 1 :(得分:0)

正如Blam所说 - 标签与列表框没有任何关系 - 我认为你在这里要做的是将具有属性Count和Name的Employees的observableCollection绑定到列表框..

为此,您需要列表框中的ItemsTemplate

<ListBox ItemSource={Binding Employees1}>
<ListBox.ItemTemplate>
  <DataTemplate>
    <StackPanel Orientation="Horizontal">
        <Label Content="{Binding Count}" />
        <Label Content="{Binding Name}" />

    </StackPanel>
  </DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

答案 2 :(得分:0)

让我试着回答问题。

ObservableCollection具有属性Count。

至于在第二个标签上获得单一财产,它正在作出一些假设 在其他版本的.NET中,您可能无法获得相同的行为 不应将显示单个值的控件绑定到集合。

如果您希望ListBox中的所选项目看到此链接

enter link description here