【问题标题】:Binding multiple controls to the object selected in combobox将多个控件绑定到组合框中选定的对象
【发布时间】:2013-04-12 06:10:12
【问题描述】:

我有一个学生班级,如下所示

public class Student
{
    public string Name { get; set; }
    public string Operator { get; set; }
    public IList<Subject> Subjects { get; set; }
}

现在我想把这个学生的集合绑定到我的窗口的三个控件上,如下图所示

<ComboBox  Margin="12,28,0,0"
           Name="cbStudents"
           VerticalAlignment="Top"
           ItemsSource="{Binding Path=PersonList}"
           DisplayMemberPath="Name"
           SelectedValuePath="Operator" />
<TextBox  Margin="12,75,0,0"
          Name="tbOperator"
          VerticalAlignment="Top"
          Text="{Binding ElementName=cbStudents,Path=SelectedValue}" />
<ComboBox Margin="12,123,0,0"
          Name="cbSubjects"
          VerticalAlignment="Top"
          ItemsSource="{Binding ElementName=cbStudents, Path=SelectedValue}"
          DisplayMemberPath="SubjectName" />

现在我担心的是,每当我更改 cbStudents 中的选择时,在这种情况下,其他控件也应该更改其相应的值。根据上面给出的代码,只要 cbStudents 中的选择更改 tbOperator 中的文本正在更改,我也想为 cbSubjects 实现相同的内容。除了有 cbStudents 的 SelectionChanged 事件之外,还有其他方法吗?

【问题讨论】:

    标签: c# .net wpf binding


    【解决方案1】:

    您希望 TextBox tbOperator 显示 ComboBox cbStudents 的 SelectedItem 的 Operator,并且另一个 ComboBox 包含 ComboBox cbStudents 的 SelectedItem 的 Subjects

    那么下面的 XAML 应该做你想做的事(删除不相关的代码来解决你的问题):

    <ComboBox Name="cbStudents" 
              ItemsSource="{Binding Path=PersonList}" 
              DisplayMemberPath="Name" />
    <TextBox Name="tbOperator" 
             Text="{Binding SelectedItem.Operator, ElementName=cbStudents}" />
    <ComboBox Name="cbSubjects" 
              ItemsSource="{Binding SelectedItem.Subjects, ElementName=cbStudents}" 
              DisplayMemberPath="SubjectName" />
    

    【讨论】:

      【解决方案2】:

      cbSubjects 的绑定路径错误。您应该将其设置为SelectedValue.Subjects:

      <ComboBox Margin="12,123,0,0" Name="cbSubjects" VerticalAlignment="Top"  ItemsSource="{Binding ElementName=cbStudents, Path=SelectedValue.Subjects}" DisplayMemberPath="SubjectName" />
      

      【讨论】:

        猜你喜欢
        • 2012-09-09
        • 1970-01-01
        • 2017-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多