显示视图时SelectedItem已更改

时间:2018-07-28 09:59:29

标签: c# .net wpf mvvm

我将创建一个ComboBox,并由用户在WPF中手动添加项。所以我创建了一些这样的代码:

我的查看代码:

<ComboBox SelectedItem="{Binding Path=SelectedItem}" ItemsSource="{Binding ItemsSource}" Text="{Binding Path=InputText, UpdateSourceTrigger=LostFocus}" IsEditable="True"/>

我的ViewModel代码:

public class ViewModel : INotifyPropertyChanged
{
    private string selectedIndex;
    private string inputText;
    public event PropertyChangedEventHandler PropertyChanged;

    public string InputText
    {
        get { return inputText; }
        set { inputText = value;  OnPropertyChanged(); CheckAndInsertIfValid(); }
    }

    public string SelectedItem
    {
        get { return selectedIndex; }
        set { selectedIndex = value; OnPropertyChanged(); }
    }

    public ObservableCollection<string> ItemsSource { get; set; }

    public ViewModel()
    {
        ItemsSource = new ObservableCollection<string>()
        {
            "0", "1", "2", "3", "4" ,"5"
        };
        SelectedItem = ItemsSource[3];
    }

    public virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private void CheckAndInsertIfValid()
    {
        if (InputText != "Some Values" && !ItemsSource.Contains(InputText))
            ItemsSource.Add(InputText);
    }

}

它工作正常,用户可以手动将其添加到ComboBox。但是,当我向用户显示视图时,SelectedItem将为“ null”。

我不知道为什么SelectedItem将为空?以及如何防止更改SelectedItem?

1 个答案:

答案 0 :(得分:0)

您的情况下,InputText属性对我来说似乎不是必需的,您可以删除它并直接绑定到SelectedItem属性:

<ComboBox SelectedItem="{Binding Path=SelectedItem}" ItemsSource="{Binding ItemsSource,Mode=TwoWay}" Text="{Binding Path=SelectedItem, UpdateSourceTrigger=LostFocus}" IsEditable="True"/>

然后大胆地更改您的VM:

 public class ViewModel : INotifyPropertyChanged
{
    private string _selectedItem;        
    public event PropertyChangedEventHandler PropertyChanged;

    public string SelectedItem
    {
        get { return _selectedItem; }
        set { _selectedItem = value; OnPropertyChanged(); CheckAndInsertIfValid(); }
    }

    public ObservableCollection<string> ItemsSource { get; set; }

    public ViewModel()
    {
        ItemsSource = new ObservableCollection<string>()
        {
            "0", "1", "2", "3", "4" ,"5"
        };
        SelectedItem = ItemsSource[3];
    }

    public virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private void CheckAndInsertIfValid()
    {
        if (SelectedItem != "Some Values" && !ItemsSource.Contains(SelectedItem))
            ItemsSource.Add(SelectedItem);
    }

}