<StackPanel>
<ComboBox ItemsSource="{Binding List1}" SelectedItem="{Binding Selected1}" />
<ComboBox ItemsSource="{Binding List2}" SelectedItem="{Binding Selected2}" />
</StackPanel>
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string property = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
readonly List<string> _list = new List<string> { "a", "b", "c", "d", "e" };
public IEnumerable<string> List1 => _list.Where(o => o != Selected2);
public IEnumerable<string> List2 => _list.Where(o => o != Selected1);
string _selected1;
public string Selected1
{
get { return _selected1; }
set
{
_selected1 = value;
OnPropertyChanged();
OnPropertyChanged(nameof(List2));
}
}
string _selected2;
public string Selected2
{
get { return _selected2; }
set
{
_selected2 = value;
OnPropertyChanged();
OnPropertyChanged(nameof(List1));
}
}
}
注意:当视图更改所选项目时,viewmodel只会触发
NotifyPropertyChanged
评估绑定中使用的属性及其值的事件。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel() { Selected1 = "a", Selected2 = "d" };
}
}