簡體   English   中英

如何在Selection Changed事件中選擇comboBox值

[英]How to Select comboBox values in Selection Changed event

I have 3 ComboBoxes in WPF form...

當我選擇第一個組合框值時,填充第二個組合框...

但是在選擇第一次comboxBox值時,其SelectionChanged事件無法正常工作。

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

這是一個更詳細的示例:

我為學生和班級寫了一個例子。 您有一堂課,上面有一個名字和一組學生。 每個學生都有一個名字。 我的課程:

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;
  }
}

我的from包含兩個組合框,我希望第一個組合框包含所有班級,第二個組合框應包含所選班級中的所有學生。 我在后面的代碼中解決了這個問題(快速又骯臟)。 我為所有類編寫了一個屬性,並模擬了一些數據。 以下是重要部分:

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"/>

完!!!

希望這個更詳細的解決方案可以幫助您理解我的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM