2017-07-03 110 views
0

我有两个组合框,两者的itemssourse是相同的。具有相同itemssource的C#多个组合框

List<string> cars = new List<string>(); 
cars.Add("Audi"); 
cars.Add("BMW"); 
cars.Add("Mercedes-Benz"); 

this.ComboBox1.ItemsSource = cars; 
this.ComboBox2.ItemsSource = cars; 

假设我在ComboBox1中选择了“奥迪”。我想要的是当在ComboBox1中选择“奥迪”时,在ComboBox2中删除/禁用“奥迪”。

有人能帮助我吗? (我是新来的C#/ WPF编程)

+1

你应该看看MVVM模式和'ICollectionView'。当你至少不知道MVVM时,很容易实现,但很难解释。 –

回答

0

公共定义2列表像

List<string> cars = new List<string>(); 
List<string> cars2 = new List<string>(); 

public CarsView() 
    { 
     InitializeComponent(); 

     cars.Add("Audi"); 
     cars.Add("BMW"); 
     cars.Add("Mercedes-Benz"); 

     this.ComboBox1.ItemsSource = cars; 
     this.ComboBox2.ItemsSource = cars; 
    } 

和你的函数必须是这样的

private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) 
     { 
      ComboBox2.SelectedIndex = -1; 
      string cb1 = ComboBox1.SelectedValue as string; 
      cars2.Clear(); 
      cars2.AddRange(cars); 
      cars2.Remove(cb1); 
      ComboBox2.ItemsSource = null; 
      ComboBox2.ItemsSource = cars2; 
     } 
0

循环throught第二组合框的项目,并检查第一个组合框中选择的项目在第二个组合框的存在,如果是的话,然后将其删除,例如:

private void comboBox1Changed(object sender, SelectionChangedEventArgs e) 
{ 
    for (int i = 0; i < comboBox2.Items.Count; i++) 
    { 
     if ((ComboBoxItem)comboBox2.Items[i] == comboBox1.SelectedItem) 
     { 
      comboBox2.Items.Remove((ComboBoxItem)comboBox2.Items[i]); 
     } 
    } 
} 

如果你想禁用项目而不从列表中删除它,因为你的下拉列表中的ListItemsEnabled属性。您可以将其设置为false以禁用它们。

+0

感谢您的答案,但我收到此错误:其他信息:无法投入'System.String'类型的对象键入'System.Windows.Controls.ComboBoxItem'。 – TestMan

+0

当他第二次更改第一个组合框时,第二个组合框将不再包含以前的项目。我会建议一个主列表,并用linq表达式更新组合框的数据源。 –

+0

@TestMan你确定你把物品铸造成了一个组合框项目,就像我在我的帖子中做的那样? '(ComboBoxItem)comboBox2.Items [i]' –

0
List<string> MasterListCars = new List<string>(); 
    List<string> TempListCars = new List<string>(); 
    public MainWindow() 
    { 
     InitializeComponent(); 
     MasterListCars.Add("Audi"); 
     MasterListCars.Add("BMW"); 
     MasterListCars.Add("Mercedes"); 
     Cb1.ItemsSource = MasterListCars; 
    } 

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     TempListCars = MasterListCars.Where(x => x != Cb1.SelectedItem.ToString()).ToList(); 
     cb2.ItemsSource = MasterListCars; 
    } 

这样你就不需要担心添加或删除的项目。 如果你想有combobox2填充在启动加入到主窗口():

cb2.ItemsSource = MasterLineCars; 
相关问题