![](/img/trans.png)
[英]WPF datagrid combobox column: how to manage event of selection changed?
[英]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.