【问题标题】:WPF - Auto refresh combobox contentWPF - 自动刷新组合框内容
【发布时间】:2011-07-19 07:34:39
【问题描述】:

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

【问题讨论】:

    标签: c# wpf mvvm combobox auto-update


    【解决方案1】:

    据我了解,您想添加一个项目并选择它。 这是如何使用 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 有 3 个属性(一个用于TextBox,另外两个用于ComboBox)和不带参数的方法AddNewItem

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

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

    因此,您必须在将添加的项目添加到集合后将其显式设置为选中。

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

    【讨论】:

      【解决方案2】:

      如果 ComboBox 绑定到 ObservableCollection,则 ComboBox 将在集合更改后立即更新。

      这就是使用 ObservableCollection 的优势 - 您无需进行任何额外的编码来更新 UI。

      如果这不是您看到的行为,也许您可​​以发布一些代码/xaml。

      【讨论】:

        猜你喜欢
        • 2012-07-28
        • 2015-02-08
        • 1970-01-01
        • 1970-01-01
        • 2012-12-09
        • 1970-01-01
        • 2012-06-19
        • 1970-01-01
        • 2023-03-14
        相关资源
        最近更新 更多