如何设置combox项可见性?

我有2个WPFcombobox(comboboxA,comboboxB)和相同的combobox项目(Apple和Orange)。 假设我在comboboxA中选择“Apple”,那么“Apple”需要隐藏在comboxB中。 如果我回到comboxA并选择“Orange”,则“Apple”将可​​见,并且“Orange”需要隐藏。 我怎样才能使用C#实现这一目标?

xaml的代码段:

        

您可以使用sa_ddam213提到的方法,或者您可以在SelectionChanged事件中强制执行它,就像这样。

 private void comboboxA_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = 0; i <= comboboxB.Items.Count -1; i++) { if (((ComboBoxItem)(comboboxB.Items[i])).Content.ToString() == ((ComboBoxItem)comboboxA.SelectedItem).Content.ToString()) { ((ComboBoxItem)(comboboxB.Items[i])).Visibility = System.Windows.Visibility.Collapsed; } else ((ComboBoxItem)(comboboxB.Items[i])).Visibility = System.Windows.Visibility.Visible; } } 

也许只是从列表中过滤所选项目

       ///  /// Interaction logic for MainWindow.xaml ///  public partial class MainWindow : Window, INotifyPropertyChanged { private string _selectedItem; private ObservableCollection _yourCollection = new ObservableCollection(); public MainWindow() { InitializeComponent(); YourCollection.Add("Apple"); YourCollection.Add("Banana"); YourCollection.Add("Pear"); YourCollection.Add("Orange"); NotifyPropertyChanged("FilteredCollection"); } // Collection Fro ComboBox A public ObservableCollection YourCollection { get { return _yourCollection; } set { _yourCollection = value; } } // ComboBox A selected Item public string SelectedItem { get { return _selectedItem; } set { _selectedItem = value; // Notify the the filter collection has changed NotifyPropertyChanged("FilteredCollection"); } } // Collection to show in ComboBox B public List FilteredCollection { // Remove the selected Item get { return _yourCollection.Where(s => !s.Equals(_selectedItem)).ToList(); } } public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } } 

或者你需要这两种方式