如何使用HashSet作为数据源在DataGridView(使用INotifyPropertyChanged) c#
本文关键字:使用 INotifyPropertyChanged DataGridView HashSet 何使用 数据源 | 更新日期: 2023-09-27 18:11:23
我试图在HashSet
中使用CC_2中的数据实现数据绑定。我已经在我的模型类中实现了INotifyPropertyChanged接口,就像这样(我在stackoverflow上找到了这个解决方案),但它仍然不会在不重置数据源的情况下改变数据网格视图。
My model class
class BookModel : INotifyPropertyChanged
{
private string name;
private uint year;
private uint pagesCount;
private string series;
private string publisher;
private string author;
private string language;
[DisplayName("Book Name")]
public string Name {
get { return name; }
set { SetField(ref name, value, "Name"); }
}
[DisplayName("Book Year")]
public uint Year {
get { return year; }
set { SetField(ref year, value, "Year"); }
}
[DisplayName("Book Series")]
public string Series {
get { return series; }
set { SetField(ref series, value, "Series"); }
}
[DisplayName("Book Pulbisher")]
public string Pulbisher {
get { return publisher; }
set { SetField(ref publisher, value, "Pulbisher"); }
}
[DisplayName("Book Author")]
public string Author {
get { return author; }
set { SetField(ref author, value, "Author"); }
}
[DisplayName("Book Language")]
public string Language {
get { return language; }
set { SetField(ref language, value, "Language"); }
}
[DisplayName("Book Pages Count")]
public uint PagesCount {
get { return pagesCount; }
set { SetField(ref pagesCount, value, "PagesCount"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetField<T>(ref T field, T value, string propertyName)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
}
创建表单时,我做
bookContainer = new HashSet<BookModel>();
dataGridViewBookList.DataSource = bookContainer.ToList();
然后点击按钮
// Creating new book from user input
bookContainer.Add(newBook);
但这只适用于
bookContainer.Add(newBook);
dataGridViewBookList.DataSource = bookContainer.ToList();
这似乎是一种"肮脏的解决方案",INotifyPropertyChanged在这种情况下没有影响。
请建议如何正确实现HashSet的数据绑定,以便在集合中数据更改(添加,删除,修改)时通知gridview
选项1-考虑使用BindingList
选项2-考虑使用这个类来代替HashSet
:
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Data.Entity;
namespace WinFormswithEFSample
{
public class ObservableListSource<T> : ObservableCollection<T>, IListSource
where T : class
{
private IBindingList _bindingList;
bool IListSource.ContainsListCollection { get { return false; } }
IList IListSource.GetList()
{
return _bindingList ?? (_bindingList = this.ToBindingList());
}
}
}
这样你也可以执行Master-Detail数据绑定。假设您有一个子类List<Product>
,那么您可以通过将List<Product>
更改为ObservableListSource<Product>
使其工作于Master-Detail数据绑定。
更多信息:数据绑定与WinForms