ListView没有在PropertyChanged事件上更新
本文关键字:事件 更新 PropertyChanged ListView | 更新日期: 2023-09-27 18:11:52
我有以下代码,但问题是,PropertyChanged总是空的,当我试图触发它。为什么会这样,我怎样才能绕过这个问题?
以编程方式创建ListView并为其添加绑定:
ListView listView = new ListView();
listView.Height = 203;
listView.Width = 501;
listView.Margin = new Thickness(0, 0, 0, 0);
Grid.SetRow(listView, 1);
Grid.SetColumn(listView, 0);
mainGrid.Children.Add(listView);
GridView myGridView = new GridView();
myGridView.AllowsColumnReorder = true;
System.Windows.Controls.GridViewColumn gvc1 = new System.Windows.Controls.GridViewColumn();
gvc1.DisplayMemberBinding = new Binding("Date");
gvc1.Header = "Date";
gvc1.Width = 100;
myGridView.Columns.Add(gvc1);
System.Windows.Controls.GridViewColumn gvc2 = new System.Windows.Controls.GridViewColumn();
gvc2.DisplayMemberBinding = new Binding("Application");
gvc2.Header = "Application";
gvc2.Width = 100;
myGridView.Columns.Add(gvc2);
System.Windows.Controls.GridViewColumn gvc3 = new System.Windows.Controls.GridViewColumn();
gvc3.DisplayMemberBinding = new Binding("Message");
gvc3.Header = "Message";
gvc3.Width = 100;
myGridView.Columns.Add(gvc3);
listView.View = myGridView;
// Create a new binding object and set the binding of this list view to it.
//rows = new ObservableCollection<Row>();
rows = new Rows();
// Create a background worker to update the rows every second.
BackgroundWorker bgworker = new BackgroundWorker();
bgworker.WorkerReportsProgress = true;
bgworker.DoWork += (doWorkSender, doWorkEventArguments) => {
for (int i = 0; i < 1000000; i++) {
Thread.Sleep(1000);
bgworker.ReportProgress(i);
}
doWorkEventArguments.Result = null;
};
bgworker.ProgressChanged += (progressChangedSender, progressChangedEventArguments) => {
rows.Add(new Row { Date = DateTime.Now.ToString(), Application = "Application", Message = "This is a sample message." });
};
bgworker.RunWorkerAsync();
listView.DataContext = rows;
Binding myBinding = new Binding();
myBinding.Source = rows;
listView.SetBinding(ItemsControl.ItemsSourceProperty, myBinding);
Row和Rows类:
public class Row {
public string Date { set; get; }
public string Application { set; get; }
public string Message { set; get; }
}
public class Rows : IEnumerable<Row>, INotifyPropertyChanged {
public List<Row> rowList { get; private set; }
public event PropertyChangedEventHandler PropertyChanged;
public Rows() {
rowList = new List<Row>();
}
public void Add(Row item) {
rowList.Add(item);
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs("rowList"));
}
else {
Console.WriteLine("PropertyChanged is null.");
}
}
public IEnumerator<Row> GetEnumerator() {
return rowList.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
将rows对象声明为rows类型:
Rows rows;
你需要实现INotifyCollectionChanged在你的类Rows
和火CollectionChanged
而不是PropertyChanged
。实际上,您不需要实现INotifyPropertyChanged
,因为没有绑定到Rows
的属性。