从源中删除在其他ComboBox中选择的项目?

时间:2013-12-05 12:37:28

标签: c# wpf mvvm combobox

假设我们在视图中有四个ComboBox(source):

<StackPanel>
    <ComboBox ItemsSource="{Binding SourceCollection1}" DisplayMemberPath="Name" SelectedItem="{Binding Selected1}"/>
    <ComboBox ItemsSource="{Binding SourceCollection2}" DisplayMemberPath="Name" SelectedItem="{Binding Selected2}"/>
    <ComboBox ItemsSource="{Binding SourceCollection3}" DisplayMemberPath="Name" SelectedItem="{Binding Selected3}"/>
    <ComboBox ItemsSource="{Binding SourceCollection4}" DisplayMemberPath="Name" SelectedItem="{Binding Selected4}"/>
</StackPanel>

VM就像(source):

public ObservableCollection<People> SourceCollection1 { get; set; }
...

private People _selected1;
public People Selected1
{
    get
    {
        return _selected1;
    }

    set
    {
        var pc = PropertyChanged;
        if (pc != null)
        {
            _selected1 = value;
            pc(this, new PropertyChangedEventArgs("Selected1"));
        }
    }
}
...

People类有两个属性:NameAge

所以,我想实现这个功能:当用户在ComboBox1中选择一个项目时,其余的ConboBox应该调整自己的ItemsSource,删除在其他ComboBox中选择的项目。

例如,应用程序启动,尚未选择任何项目。然后,用户在people A中选择ComboBox1,因此当用户打开ComboBox2下拉列表时,people A项不应包含在ComboBox2来源中。因此,当用户在eople B中选择p ComboBox2时,ComboBox3不应该有people Apeople B。等等...

有没有人有一些不错的解决方案?

1 个答案:

答案 0 :(得分:1)

这可行:

public People Selected1
{
    get
    {
        return _selected1;
    }

    set
    {
        var pc = PropertyChanged;
        UpdateList (SourceCollection2, _selected, value);
        if (pc != null)
        {
            _selected1 = value;
            pc(this, new PropertyChangedEventArgs("Selected1"));
        }

    }
}

private void UpdateList(ObservableCollection<People> list, People oldItem, People newItem){
    if(!list.Contains(oldItem)){
        list.Add(oldItem);
    }
    if(list.Contains(newItem)){
        list.Remove(newItem);
    }
}
相关问题