在任何变量发生变化时触发事件

时间:2013-02-13 14:21:02

标签: c# events variables

我有一个表单,显示有关程序变量的信息。所以知道我想在任何变量发生变化时更新表单。有没有办法触发事件或类似事件?

2 个答案:

答案 0 :(得分:3)

没有这样的能力,除非你自己编写代码或使用一些超级高级代码检测工具。

我建议您使用属性而不是字段(除非您实际上是指局部变量?)并实现INotifyPropertyChanged接口。

答案 1 :(得分:0)

有很多方法,但我使用的是可观察的collectionchanged事件,因此无论事件被触发,它都会像下面那样进行操作......

static void ObservableEmployees_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                 case NotifyCollectionChangedAction.Add:
                    Console.WriteLine("New item {0} added in the collection",e.NewItems[0].ToString());
                    break;
                case NotifyCollectionChangedAction.Remove:
                    Console.WriteLine("Old item {0} removed in the collection", e.OldItems[0].ToString());
                    break;
                case NotifyCollectionChangedAction.Move:
                    Console.WriteLine("item {0} is moved", e.NewItems[0].ToString());
                    break;
                case NotifyCollectionChangedAction.Replace:
                    Console.WriteLine("item{0} is replacced by item{1}.", e.OldItems[0].ToString(), e.NewItems[0].ToString());
                    break;
                case NotifyCollectionChangedAction.Reset:
                    Console.WriteLine("itme{0} is reset.", e.OldItems[0].ToString());
                    break;

}

和订阅..

observableEmployees = new ObservableCollection<Employee>();

            observableEmployees.CollectionChanged += ObservableEmployees_CollectionChanged;
相关问题