我有一个列表框:WPF/C#更新属性更改到ListBox
<ListBox x:Name="lbxAF" temsSource="{Binding}">
,从这个来自这个修改观察到的集合中获取数据:
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不执行INotifiyPropertyChanged ...还你怎么在视图模型/代码隐藏文件名的更新? – Nitin