我坚持在C#WPF中使用Linq在组合框(父级)和listview(子级)控件之间创建主细节关系。
protected class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender{ get; set; }
}
protected static List<Student> students = new List<Student>
{
new Student {FirstName = "Terry", LastName = "Adams", Gender= "M"},
new Student {FirstName = "Terry2", LastName = "Adams", Gender= "M"},
new Student {FirstName = "Karry", LastName = "Adams2", Gender= "F"},
new Student {FirstName = "Karry2", LastName = "Adams4", Gender= "F"},
}
Combobox将由Gender groubby()生成,listview将根据组合框选择进行更新。这样的东西但不起作用,谢谢
var result = (from cat in students
select new {
FirstName = cat.FirstName ,
LastName = cat.LastName}).Distinct().ToList();
答案 0 :(得分:3)
可能有更好的方法在listview中实际设置数据,但是我对WPF并不太熟悉,但linq似乎是正确的。
comboBox1.ItemsSource = students.Select(x => x.Gender).Distinct();
private void SelectionChanged(object sender, SelectionChangedEventArgs e)
{
listView1.ItemsSource = students
.Where(x => x.Gender == comboBox1.SelectedItem.ToString()).ToList();
}
学生需要覆盖ToString()
public override string ToString()
{
return string.Format("{0} {1}", FirstName, LastName);
}
答案 1 :(得分:2)
你在找这个吗?
示例代码:
var result = (from cat in students
select new
{
FirstName = cat.FirstName,
LastName = cat.LastName,
Gender = cat.Gender
}).Distinct().ToList().Where(oc=>oc.Gender == comboBox1.SelectedItem.ToString());
答案 2 :(得分:1)
试试这个解决方案:
//For Combobox (You can
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var AllGender = (from cat in students select cat.Gender).Distinct();
foreach (var gender in AllGender)
{
comboBox1.Items.Add(gender.ToString());
}
}
//For ListBox
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selectedValue = comboBox1.SelectedItem.ToString();
var studentList = from student in students
where student.Gender == selectedValue
select new { Firstname = student.FirstName, LastName = student.LastName };
listBox1.Items.Clear();
foreach (var student in studentList)
{
listBox1.Items.Add(student.Firstname + " " + student.LastName);
}
}
希望它有所帮助。