【问题标题】:C# - How to get dependent combobox values from custom classesC# - 如何从自定义类中获取依赖的组合框值
【发布时间】:2016-05-31 12:50:01
【问题描述】:

我有一个ListForTesting 类型为TestID 的列表。

 List<HelpClass.TestID> ListForTesting;

    //Populating the list
    HelpClass.TestID TestObject = new HelpClass.TestID();
    .
    .
    //data here
    .
    .
    TestObject.Manoeuvres = new List<HelpClass.ManoeuvresID>();
    HelpClass.ManoeuvresID Manoeuvre = new HelpClass.ManoeuvresID();
    .
    .
    //more data here
    .
    .
TestObject.Manoeuvres.Add(Manoeuvre);
ListForTesting.Add(TestObject);

我正在使用该列表在组合框中获取下拉列表

combobox_testType.ItemsSource = ListForTesting.Select(t => t.testName);

然后我有另一个组合框,它依赖于第一个组合框,我想要如下所示。

combobox_manouevre.ItemsSource = ListForTesting[selectedindexfromfirstcombobox].Manoeuvres.Select(t => t.manName);

【问题讨论】:

  • 有人吗?在这里需要一些帮助

标签: c# wpf list combobox


【解决方案1】:

我认为你可以这样做:

combobox1.ItemsSource = ListForTesting;
combobox1.DisplayMember= "testName";
combobox1.ValueMember= "id";

在 combobox1 的 selectedChanged 事件中:

combobox2.ItemsSource = ListForTesting.Where(x => x.id == combobox1.SelectedValue).Manoeuvres;
combobox2.DisplayMember= "manName";
combobox2.ValueMember= "idManoeuvre";

【讨论】:

  • 它告诉我“运算符'=='不能应用于'int'和'object'类型的操作数”这是在WPF中
  • 我已通过x.testName == combobox_testType.SelectedValue.ToString() 修复,但无法让.Manoeuvres 的最后一部分工作
  • 在您的示例中,您有 2 个不同的组合框,对吗?为什么两者都命名为“combobox_testType”?复制/粘贴错误还是在您的代码中是这样的?你能告诉我你的代码和你的修改吗?
  • @c.changon 你是对的,复制/粘贴是错误的。你现在能帮忙吗?
【解决方案2】:

我不确定这是否是最合适的答案,但它在第二个组合框中确实有效。

combobox_manouevre.ItemsSource = ListForTesting.Where(x =&gt; x.testName == combobox_testType.SelectedValue.ToString()).SelectMany(l=&gt;l.Manoeuvres).Select(o=&gt;o.manName);

【讨论】:

    【解决方案3】:

    为了提高代码的可见性,您可以这样做:

    combobox_manouevre.ItemsSource = ListForTesting.Where(x => x.testName == combobox_testType.SelectedValue.ToString()).FirstOrDefault().Manoeuvres;
    combobox_manouevre.DisplayMember = "manName";
    combobox_manouevre.ValueMember = "yourIdManoeuvre";
    

    使用 DisplayMember 和 ValueMember 将组合框中显示的值与值 (id) 分开会更安全。

    例如:

    机动清单:

    id= 1 name= "manoeuvre1"  
    id= 2 name= "manoeuvre1" // (same name that id=1)  
    id= 3 name= "manoeuvre2"
    

    如果您选择第二个“manoeuvre1”,则 id 将为 2,您将使用此 id(不会出错)

    你的 ListForTesting 列表也一样

    【讨论】:

    • 在 WPF 中,DisplayMember = DisplayMemberPath 和 ValueMember = SelectedValuePath。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    相关资源
    最近更新 更多