我有一个从我的代码的大部分内容引用的模型集合。
public class TraceEntryQueue
{
private readonly Queue<TraceEntry> _logEntries;
public TraceEntryQueue()
{
_logEntries = new Queue<TraceEntry>();
}
public void AddEntry(TraceEntry newEntry)
{
_logEntries.Enqueue(newEntry);
}
public List<TraceEntry> GetAsList()
{
return _logEntries.ToList();
}
}
此系列在我的一个观点中展示。
public class LoggingViewModel : ViewModelBase
{
private ICollectionView _customers;
public ICollectionView Customers
{
get
{
return _customers;
}
private set
{
_customers = value;
}
}
public LoggingViewModel(TraceEntryQueue traceQueue)
{
Customers = CollectionViewSource.GetDefaultView(traceQueue.GetAsList());
Customers.SortDescriptions.Add(new SortDescription("Index", ListSortDirection.Descending));
Customers.Refresh();
}
}
问题是当我通过
添加新条目时,如何通知我的视图重新加载集合 public void AddEntry(TraceEntry newEntry)
{
_logEntries.Enqueue(newEntry);
}
答案 0 :(得分:1)
使用可观察集合而不是队列。这将在更新集合时自动通知您的视图(添加/删除等)
public class TraceEntryQueue
{
private readonly ObservableCollection<TraceEntry> _logEntries;
public TraceEntryQueue()
{
_logEntries = new ObservableCollection<TraceEntry>();
}
public void AddEntry(TraceEntry newEntry)
{
_logEntries.Add(newEntry);
}
public ObservableCollection<TraceEntry> GetLogEntries()
{
return _logEntries;
}
}
答案 1 :(得分:0)
public class TraceEntryQueue
{
private readonly Queue<TraceEntry> _logEntries;
private readonly ICollectionView _logEntriesView;
public TraceEntryQueue()
{
_logEntries = new Queue<TraceEntry>();
_logEntriesView = CollectionViewSource.GetDefaultView(logEntries.ToList());
}
//....
public void AddEntry(TraceEntry newEntry)
{
_logEntries.Enqueue(newEntry);
_logEntriesView.SourceCollection = logEntries.ToList();
_logEntriesView.Refresh();
}
public ICollectionView GetAsView()
{
return _logEntriesView;
}
}
使用GetAsView
并直接绑定到您的datagrid / listbox / listview。
答案 2 :(得分:0)
正如@RobJohnson所提到的,你可以使用一个ObservableCollection。但是,如果您需要创建自己的集合类,则应实现INotifyCollectionChanged接口:
public class TraceEntryQueue : INotifyCollectionChanged
{
private readonly Queue<TraceEntry> _logEntries;
public TraceEntryQueue()
{
_logEntries = new Queue<TraceEntry>();
}
public void AddEntry(TraceEntry newEntry)
{
_logEntries.Enqueue(newEntry);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newEntry));
}
public List<TraceEntry> GetAsList()
{
return _logEntries.ToList();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
{
CollectionChanged(this, e);
}
}
}