如何在Selection Changed事件中选择comboBox值

时间:2012-10-29 14:07:51

标签: c# wpf

I have 3 ComboBoxes in WPF form...

当我选择第一个combox Box值时,它会填充第二个ComboBox ...

但是在选择第一次comboxBox值时,其SelectionChanged事件无效...... 选择第二次工作后......

 private void cmbBoard_SelectionChanged(object sender, SelectionChangedEventArgs e)
    { cmbClass.ItemsSource = dt.DefaultView;
                    cmbClass.DisplayMemberPath = "Class";
                    cmbClass.SelectedValuePath = "ClassID";
                    cmbClass.SelectedIndex = 0;
    }

1 个答案:

答案 0 :(得分:3)

这是一个更详细的例子:

我写了一个学生和班级的例子。 你有一个有名字和学生集合的班级。 每个学生都有一个名字。 我的课程:

public class Class
{
  public string Name
  {
    get;
    set;
  }

  public Collection<Student> Students
  {
    get;
    set;
  }

  public Class( string name, Collection<Student> students )
  {
    this.Name = name;
    this.Students = students;
  }
}

public class Student
{
  public string Name
  {
    get;
    set;
  }

  public string FirstName
  {
    get;
    set;
  }

  public string Fullname
  {
    get
    {
      return string.Format( "{0}, {1}", this.Name, this.FirstName );
    }
  }

  public Student(string name, string firstname)
  {
    this.Name = name;
    this.FirstName = firstname;
  }
}

我的包含两个组合框,我希望第一个包含所有类,第二个应包含所选类中的所有学生。 我在后面的代码中解决了这个问题(快速而肮脏)。我为所有类编写了一个属性并模拟了一些数据。以下是重要部分:

public Collection<Class> Classes
{
  get;
  set;
}

public MainWindow()
{
  this.InitializeComponent( );
  this.Classes = new Collection<Class>( )
  {
    new Class("Class 1",
      new Collection<Student>()
      {new Student("Caba", "Milagros"),
        new Student("Wiltse","Julio"),
        new Student("Clinard","Saundra")}),

    new Class("Class 2",
      new Collection<Student>()
      {new Student("Cossette", "Liza"),
        new Student("Linebaugh","Althea"),
        new Student("Bickle","Kurt")}),

    new Class("Class 3",
      new Collection<Student>()
      {new Student("Selden", "Allan"),
        new Student("Kuo","Ericka"),
        new Student("Cobbley","Tia")}),
  };
  this.DataContext = this;
    }

现在我创建了第一个名为cmbClass的组合框。

<ComboBox x:Name="cmbClass"
              ItemsSource="{Binding Classes}"
              DisplayMemberPath="Name"
              Margin="10"
              Grid.Row="0"/>

之后我创建了第二个组合框。但是要获取itemsSource,我需要第一个框中的值。所以我使用元素绑定从第一个框中获取值。

Binding ElementName=cmbClass

我对第一个框的SelectedItem感兴趣,因为这个项目包含了所有需要的学生的集合(参见上面的课程)。所以我使用path属性来解决这个问题。 我的第二个组合框:

<ComboBox ItemsSource="{Binding ElementName=cmbClass, Path=SelectedItem.Students}"
          DisplayMemberPath="Fullname"
          Margin="10"
          Grid.Row="1"/>

完成!!!

希望这个更详细的解决方案可以帮助您了解我的方式。