我有2个WPF组合框(comboboxA,comboboxB)和相同的组合框项目(Apple& Orange)。假设我在comboboxA中选择“Apple”,那么“Apple”需要隐藏在comboxB中。如果我回到comboxA并选择“Orange”,则“Apple”将可见,并且“Orange”需要隐藏。如何使用C#实现这一目标?
xaml的代码段:
<ComboBox Name="comboboxA" >
<ComboBoxItem Content="Apple" Name="AppleA"></ComboBoxItem>
<ComboBoxItem Content="Orange" Name="OrangeA"></ComboBoxItem>
</ComboBox>
<ComboBox Name="comboboxB" >
<ComboBoxItem Content="Apple" Name="AppleB"></ComboBoxItem>
<ComboBoxItem Content="Orange" Name="OrangeB"></ComboBoxItem>
</ComboBox>
答案 0 :(得分:4)
你可以使用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;
}
}
答案 1 :(得分:2)
可能只是过滤列表中的选定项目
<Window x:Class="WpfApplication6.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Name="UI">
<Grid>
<ComboBox ItemsSource="{Binding ElementName=UI,Path=YourCollection}" SelectedItem="{Binding ElementName=UI,Path=SelectedItem}" Height="23" HorizontalAlignment="Left" Margin="65,61,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" />
<ComboBox ItemsSource="{Binding ElementName=UI, Path=FilteredCollection}" Height="23" HorizontalAlignment="Left" Margin="223,61,0,0" Name="comboBox2" VerticalAlignment="Top" Width="120" />
</Grid>
</Window>
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
private string _selectedItem;
private ObservableCollection<string> _yourCollection = new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent();
YourCollection.Add("Apple");
YourCollection.Add("Banana");
YourCollection.Add("Pear");
YourCollection.Add("Orange");
NotifyPropertyChanged("FilteredCollection");
}
// Collection Fro ComboBox A
public ObservableCollection<string> 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<string> 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));
}
}
}
或者您是否需要双向工作