c# - 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 时,旧项目仍然存在并且没有任何更新。
解决方案
您正在覆盖 _defaultItems 的值。这不是Observable
in ObservableCollection
所做的。instance
您应该始终保持集合相同,并且仅从中添加()和删除()。
用新集合完全替换旧集合的一种方法是:
// Update Method
private void UpdateList(List<String> newList)
{
DefaultItems.Clear();
DefaultItems.AddRange(newItems);
}
请注意,这是低效的,并且 ObservableCollection 将在每次添加项目时更新视图。有一些方法可以解决这个问题,比如在 AddRange 完成之前暂停通知。
推荐阅读
- spring-boot - th:field="${something}" 和 th:field="*{something}" 有什么区别?
- javascript - javascript导出语法之间有什么区别?
- html - 如何从 FileList 中的视频中获取预览图像?HTML 反应
- deep-learning - 如何从 MRI 切片中获取通道 = 3?
- razor - Asp.net core 3.0 razor pages - 从列表创建动态网格
- apache-nifi - 如何在 nifi 中增加 Base64EncodeContent 1.9.2 组大小限制
- ios - 使用 Codable 解析嵌套的无键 JSON
- node.js - 从批量操作更新时不调用 Pre Update 中间件
- python - UnicodeEncodeError:“latin-1”编解码器无法对位置 0-9 中的字符进行编码:序数不在范围内(256)
- python - 欧几里得距离的python数据框