gpt4 book ai didi

c# - WPF/C# 将 ObservableCollection 中的项目的属性更改更新到 ListBox

转载 作者:行者123 更新时间:2023-11-30 13:19:39 29 4
gpt4 key购买 nike

我有一个列表框:

<ListBox x:Name="lbxAF" temsSource="{Binding}">

从这个修改后的 Observable 集合中获取数据:

public ObservableCollectionEx<FileItem> folder = new ObservableCollectionEx<FileItem>();

它是在一个类中创建的,该类使用 FileSystemWatcher 来监视特定文件夹的文件添加、删除和修改。

ObservableCollection 已修改(因此最后是 Ex),以便我可以从外部线程修改它(代码不是我的,我实际上在这个网站上做了一些搜索并找到了它,就像一个魅力):

    // This is an ObservableCollection extension
public class ObservableCollectionEx<T> : ObservableCollection<T>
{
// Override the vent so this class can access it
public override event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged;

protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
using (BlockReentrancy())
{
System.Collections.Specialized.NotifyCollectionChangedEventHandler eventHanlder = CollectionChanged;
if (eventHanlder == null)
return;

Delegate[] delegates = eventHanlder.GetInvocationList();

// Go through the invocation list
foreach (System.Collections.Specialized.NotifyCollectionChangedEventHandler handler in delegates)
{
DispatcherObject dispatcherObject = handler.Target as DispatcherObject;

// If the subscriber is a DispatcherObject and different thread do this:
if (dispatcherObject != null && dispatcherObject.CheckAccess() == false)
{
// Invoke handler in the target dispatcher's thread
dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, this, e);
}
// Else, execute handler as is
else
{
handler(this, e);
}
}
}
}
}

集合由以下部分组成:

public class FileItem
{
public string Name { get; set; }
public string Path { get; set; }
}

它允许我存储文件的名称和路径。

就文件的删除和添加而言,一切都很好,列表框针对这两个文件得到完美更新...但是,如果我更改任何文件的名称,它不会更新列表框。

如何将 FileItem 属性的更改通知列表框?我假设 ObservableCollection 会处理这个问题,但显然它仅在添加或删除 FileItem 时引发标志,而不是在其内容更改时引发标志。

最佳答案

您的 FileItem 类应该实现 INotifyPropertyChanged。下面是它的一个简单的工作实现。

public class FileItem : INotifyPropertyChanged
{
private string _Name;

public string Name
{
get { return _Name; }
set {
if (_Name != value)
{
_Name = value;
OnPropertyChanged("Name");
}
}
}

private string _Path;

public string Path
{
get { return _Path; }
set {
if (_Path != value)
{
_Path = value;
OnPropertyChanged("Path");
}
}
}

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}


}

关于c# - WPF/C# 将 ObservableCollection 中的项目的属性更改更新到 ListBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18731608/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com