WPF中监视DependencyProperty的变化
周银辉
尽管一个类会提供很多事件,但有时候还是显得不够,比如说前两天我就以为WPF的ListBox控件会有ItemsSourceChanged事件,但好像没有。这里有一个方法可以监视任何一个DependencyProperty的Changed,下面是demo:
public class People : DependencyObject { public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof (string), typeof (People), new PropertyMetadata(default(string))); public string Name { get { return (string) GetValue(NameProperty); } set { SetValue(NameProperty, value); } } } //......... private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { var people = new People {Name = "zhang san"}; var descriptor = DependencyPropertyDescriptor.FromProperty(People.NameProperty, typeof (People)); descriptor.AddValueChanged(people, (o, args) => MessageBox.Show("name changed to " + people.Name)); people.Name = "Li si"; }