0

我坚持在 C# WPF 中使用 Linq 在组合框(父)和列表视图(子)控件之间创建主细节关系。

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"},
}

组合框将由 Gender groubby() 生成,列表视图将根据组合框选择进行更新。像这样的东西,但不起作用,谢谢

var result = (from cat in students 
               select new {
               FirstName = cat.FirstName ,                                         
               LastName = cat.LastName}).Distinct().ToList();
4

3 回答 3

3

可能有更好的方法来实际设置列表视图、组合框中的数据,但我对 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);        
    }
于 2013-08-03T09:48:11.970 回答
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());
于 2013-08-03T09:40:28.337 回答
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);
        }

    }

希望能帮助到你。

于 2013-08-03T09:38:55.620 回答