首页 > 解决方案 > UserControl ComboBox 未更新

问题描述

我创建了UserControl DefaultComboBox

<UserControl x:Class="MyProject.ComboBoxes.DefaultComboBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <ComboBox x:Name="ComboBoxDefault"
          ItemsSource="{Binding DefaultItems, UpdateSourceTrigger=PropertyChanged}" />
    </Grid>
</UserControl>

ComboBox UserControl的CodeBehind :

public partial class DefaultComboBox : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private ObservableCollection<String> _defaultItems = new ObservableCollection<String>();

    public ObservableCollection<string> DefaultItems
    {
        get { return _defaultItems; }
        set
        {
            _defaultItems = value;
            NotifyPropertyChanged(DefaultItems);
        }
    }

    // Constructor
    public DefaultComboBox()
    {
        UpdateList(ExternalSource.InitialItemList);
        NotifyPropertyChanged("DefaultItems");

        InitializeComponent();
    }

    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    // Some DependencProperties like Filter

    // Update Method
    private void UpdateList(List<String> newList)
    {
        DefaultItems = new ObservableCollection<string>(newList);
        NotifyPropertyChanged("DefaultItems");
    }
}

这是使用控件的示例:

<comboBoxes:DefaultComboBox x:Name="DefaultComboBoxUserView"
                            Filter="{Binding FilterString}"/>

问题:

如果我第一次启动我的 WPF 应用程序并调用 DefaultComboBox 的构造函数,则 UpdateList 方法有效并且 ComboBox 包含预期的项目。

如果我在运行时使用 UpdateList 方法,则会调用 DefaultItems 的设置器并且项目已正确更新,但是当我在组合框下拉菜单中单击 GUI 时,旧项目仍然存在并且没有任何更新。

标签: c#.netwpfcomboboxuser-controls

解决方案


您正在覆盖 _defaultItems 的值。这不是Observablein ObservableCollection所做的。instance您应该始终保持集合相同,并且仅从中添加()和删除()。

用新集合完全替换旧集合的一种方法是:

// Update Method
private void UpdateList(List<String> newList)
{
    DefaultItems.Clear();
    DefaultItems.AddRange(newItems);
}

请注意,这是低效的,并且 ObservableCollection 将在每次添加项目时更新视图。有一些方法可以解决这个问题,比如在 AddRange 完成之前暂停通知。


推荐阅读