B.K*_*.K. 3 c# wpf listbox observablecollection
我有一个列表框:
<ListBox x:Name="lbxAF" temsSource="{Binding}">
Run Code Online (Sandbox Code Playgroud)
从这个修改过的Observable Collection中获取数据:
public ObservableCollectionEx<FileItem> folder = new ObservableCollectionEx<FileItem>();
Run Code Online (Sandbox Code Playgroud)
这是在使用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);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
该系列由以下组成:
public class FileItem
{
public string Name { get; set; }
public string Path { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这允许我存储文件的名称和路径.
就删除和添加文件而言,一切都很有效,并且列表框可以完美地更新这两个... 但是,如果我更改任何文件的名称,它不会更新列表框.
如何通知列表框中FileItem属性的更改?我假设ObservableCollection将处理它,但显然它只在添加或删除FileItem时引发标志,而不是在其内容被更改时引发.
Ana*_*ali 10
你的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));
}
}
Run Code Online (Sandbox Code Playgroud)
这就是ObservableCollection工作原理 - 它仅监控项目的插入/删除/移动。
要在每个项目(或FileItem在您的情况下)更改时更新视图,FileItem必须INotifyPropertyChanged在您设置要观察的每个属性时实现并触发适当的事件。
以下是如何执行此操作的示例:http : //msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx