本帖最后由 Richard.Ma 于 2021-8-31 11:20 编辑
BindingList中的对象如果实现了INotifyPropertyChanged接口,那么在flexgrid编辑数据后,就可以触发BindingList的ListChanged事件,然后可以给这个项目打一个Dirty的标记(比如可以加一个status属性专门存储状态)
参考下面的代码,创建了一个实现了INotifyPropertyChanged的类Product
- static class MyData
- {
- public static string[] country = new string[] { "中国", "美国", "日本" };
- public static string[] product = new string[] { "苹果", "菠萝", "香蕉" };
- public static BindingList<Product> GetProductList(int num)
- {
- BindingList<Product> list = new BindingList<Product>();
- Random r = new Random();
- for (int i = 0; i < num; i++)
- {
- list.Add(
- new Product()
- {
- Id = i,
- Country = country[r.Next(3)],
- Name = product[r.Next(3)],
- Date = DateTime.Now.AddDays(r.Next(1000) - 1000),
- Price = r.Next(10, 100),
- Count = r.Next(1, 5),
- Status= Status.NoChange
- }
- );
- }
- return list;
- }
- }
- public class Product:INotifyPropertyChanged
- {
- private int id;
- private string country;
- private string name;
- private DateTime date;
- private int price;
- private int count;
- private Status status;
- public int Id { get => id; set => id = value; }
- public string Country { get => country; set {country = value;NotifyPropertyChanged("Country");}}
- public string Name { get => name; set { name = value; NotifyPropertyChanged("Name"); } }
- public DateTime Date { get => date; set { date = value; NotifyPropertyChanged("Date"); } }
- public int Price { get => price; set { price = value; NotifyPropertyChanged("Price"); } }
- public int Count { get => count; set { count = value; NotifyPropertyChanged("Count"); } }
- public Status Status { get => status; set => status = value; }
- public event PropertyChangedEventHandler PropertyChanged;
- protected virtual void NotifyPropertyChanged(string propertyName)
- {
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
- }
- }
- }
- public enum Status
- {
- Modified,
- Added,
- Removed,
- NoChange
- }
复制代码
然后在Forms中的BindingList的ListChanged 事件中,
- BindingList<Product> list = MyData.GetProductList(10);
- public Form1()
- {
- InitializeComponent();
-
- c1FlexGrid1.DataSource = list;
-
- list.ListChanged += List_ListChanged;
- }
- private void List_ListChanged(object sender, ListChangedEventArgs e)
- {
- if(e.ListChangedType== ListChangedType.ItemChanged)
- {
- list[e.NewIndex].Status = Status.Modified;
- }
- else if (e.ListChangedType == ListChangedType.ItemAdded)
- {
- list[e.NewIndex].Status = Status.Added;
- }
- else if (e.ListChangedType == ListChangedType.ItemDeleted)
- {
- list[e.NewIndex].Status = Status.Removed;
- }
- }
复制代码
|