WPF - 自动刷新组合框的内容 [英] WPF - Auto refresh combobox content

查看:254
本文介绍了WPF - 自动刷新组合框的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到的样本MVVM应用程序。用户界面有一个文本框,一个按钮和一个组合框。当我输入在文本框中的东西,按下按钮,我输入的文本被添加到一个ObservableCollection。组合框被绑定到该集合。我如何获得组合框全自动显示新添加字符串?

I got a sample mvvm app. The UI has a textbox, a button and a combobox. when I enter something in the textbox and hit the button, the text I enter gets added to an observablecollection. The Combobox is bound to that collection. How do I get the combobox to display the newly added string automaticly?

推荐答案

据我理解正确的话,您要添加的项并选择它。
下面是例子,如何可以使用视图模型和绑定完成

As I understand correctly, you want to add an item and select it. Here is the example how it can be done using ViewModel and bindings.

XAML中:

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



视图模型:

ViewModel:

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 有3个属性(一个用于文本框和另外两名为组合框)和方法 AddNewItem 不带参数。

The MainViewModel has 3 properties (one for the TextBox and two other for the ComboBox) and the method AddNewItem without parameters.

该方法可以从命令触发,但对于命令没有标准类,所以我将其称之为从后台代码:

The method can be triggered from a command, but there is no standard class for commands, so I will call it from the code-behind:

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



因此​​,作为选择将其添加到集合后,必须明确设置添加的项目。

So you must explicitly set an added item as selected after you add it to a collection.

由于该方法 OnItemsChanged 组合框类>被保护, 'T被使用。

Because the method OnItemsChanged of the ComboBox class is protected and can't be used.

这篇关于WPF - 自动刷新组合框的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆