WPF - 自动刷新组合框内容

Ols*_*sen 6 c# wpf combobox auto-update mvvm

我有一个示例mvvm应用程序.UI具有文本框,按钮和组合框.当我在文本框中输入内容并点击按钮时,我输入的文本被添加到observablecollection中.Combobox与该系列绑定.如何让组合框自动显示新添加的字符串?

vor*_*olf 5

据我所知,你想添加一个项目并选择它.以下是使用ViewModel和绑定如何完成的示例.

XAML:

<StackPanel>
    <TextBox Text="{Binding ItemToAdd}"/>
    <ComboBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />
    <Button Content="Add" Click="Button_Click"/>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

视图模型:

public class MainViewModel:INotifyPropertyChanged
{
    public ObservableCollection<string> Items { get; set; }

    public string ItemToAdd { get; set; }

    private string selectedItem;

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

    public void AddNewItem()
    {
        this.Items.Add(this.ItemToAdd);
        this.SelectedItem = this.ItemToAdd;
    }


    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

MainViewModel有3个属性(一个用于,TextBox另外两个用于ComboBox)和AddNewItem没有参数的方法.

该方法可以从命令触发,但命令没有标准类,所以我将从代码隐藏中调用它:

   ((MainViewModel)this.DataContext).AddNewItem();
Run Code Online (Sandbox Code Playgroud)

因此,在将其添加到集合后,必须将添加的项明确设置为已选中.

由于该方法OnItemsChanged的的ComboBox类被保护,不能被使用.