如果它不是ItemsSource的一部分,则自动从ComboBox中清除SelectedValue

时间:2017-04-27 13:29:16

标签: wpf xaml mvvm

我的WPF应用程序中ComboBoxes使用SelectedValueSelectedValuePath进行了选择。有时SelectedValue不属于ItemsSource(因为数据库不一致)。

示例:

Items = new ObservableCollection<Item>()
{
    new Item() { Id = "1", Text = "Text 1" },
    new Item() { Id = "2", Text = "Text 2" },
};

SelectedValue = "3";

当加载ComboBox且未选择其他值时,SelectedValue属性仍然是不一致的值(示例中为“3”)。当SelectedValue不属于ItemsSource时,有没有办法让绑定自动清除<ComboBox ItemsSource="{Binding Items}" SelectedValuePath="Id" SelectedValue="{Binding SelectedValue, Mode=TwoWay}" DisplayMemberPath="Text" />

查看:

public class MainWindowViewModel : ViewModel
{
    public MainWindowViewModel()
    {
        Items = new ObservableCollection<Item>()
        {
            new Item() {Id ="1", Text = "Text 1" },
            new Item() {Id ="2", Text = "Text 2" },
        };

        SelectedValue = "3";
    }

    private ObservableCollection<Item> items;

    public ObservableCollection<Item> Items
    {
        get { return items; }
        set { items = value; OnPropertyChanged(); }
    }

    private string selectedValue;

    public string SelectedValue
    {
        get { return selectedValue; }
        set { selectedValue = value; OnPropertyChanged(); }
    }
}

public class Item
{
    public string Id { get; set; }

    public string Text { get; set; }

}

视图模型:

#uniqueID input[type=file]::-ms-value {
    position: absolute !important;
    left: -9999px !important;
    text-align: right !important;
 }

1 个答案:

答案 0 :(得分:4)

这个逻辑应该在视图模型中实现,即当SelectedValue中没有这样的项目时,你永远不应该将Items设置为3。然后将视图模型设置为无效状态。

因此,您不应尝试在视图或控件中实现此类逻辑,而应在其所属的视图模型中实现它。它应该很简单:

SelectedValue = "3";
if (!Items.Any(x => x.Id == SelectedValue))
    SelectedValue = null;

或者在二传手中:

public string SelectedValue
{
    get { return selectedValue; }
    set
    {
        selectedValue = value;
        if (!Items.Any(x => x.Id == SelectedValue))
            selectedValue = null;
        OnPropertyChanged();
    }
}