WPF - 自动刷新下拉框内容

6

我有一个MVVM应用程序的示例。UI包含一个文本框、一个按钮和一个组合框。当我在文本框中输入一些内容并点击按钮时,我输入的文本将被添加到ObservableCollection中。组合框绑定到该集合。如何使组合框自动显示新添加的字符串?

2个回答

5

我的理解是,您想要添加一个项目并选择它。

以下是使用 ViewModel 和绑定完成此操作的示例。

Xaml:

<StackPanel>
    <TextBox Text="{Binding ItemToAdd}"/>
    <ComboBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />
    <Button Content="Add" Click="Button_Click"/>
</StackPanel>

视图模型:

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));
        }
    }
}

MainViewModel有三个属性(一个是TextBox,另外两个是ComboBox),还有一个不带参数的AddNewItem方法。

该方法可以通过命令触发,但没有标准的命令类,因此我将在代码后台中调用它:

   ((MainViewModel)this.DataContext).AddNewItem();

当你将一个项目添加到集合中后,必须明确地将其设置为选定状态。

因为ComboBox类的方法OnItemsChanged是受保护的,不能使用。


3
如果ComboBox绑定了一个ObservableCollection,那么只要集合发生变化,ComboBox就会被更新。
这就是使用ObservableCollection的优点——您不需要编写任何额外的代码来更新UI。
如果您没有看到这种行为,也许您可以发布一些代码/XAML。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接