属性更改时引发事件

当属性的值改变时,我需要引发一个事件。就我而言,这是更改 webView.Source 的时间。我无法创建派生类,因为该类被标记为已密封。有没有办法引发事件?



当年话下
浏览 196回答 2
2回答

万千封印

属性更改时引发事件对于这种情况,您可以创建一个DependencyPropertyWatcher来检测DependencyProperty更改的事件。下面是可以直接使用的工具类。public class DependencyPropertyWatcher<T> : DependencyObject, IDisposable{&nbsp; &nbsp; public static readonly DependencyProperty ValueProperty =&nbsp; &nbsp; &nbsp; &nbsp; DependencyProperty.Register(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Value",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; typeof(object),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; typeof(DependencyPropertyWatcher<T>),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new PropertyMetadata(null, OnPropertyChanged));&nbsp; &nbsp; public event DependencyPropertyChangedEventHandler PropertyChanged;&nbsp; &nbsp; public DependencyPropertyWatcher(DependencyObject target, string propertyPath)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; this.Target = target;&nbsp; &nbsp; &nbsp; &nbsp; BindingOperations.SetBinding(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ValueProperty,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new Binding() { Source = target, Path = new PropertyPath(propertyPath), Mode = BindingMode.OneWay });&nbsp; &nbsp; }&nbsp; &nbsp; public DependencyObject Target { get; private set; }&nbsp; &nbsp; public T Value&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get { return (T)this.GetValue(ValueProperty); }&nbsp; &nbsp; }&nbsp; &nbsp; public static void OnPropertyChanged(object sender, DependencyPropertyChangedEventArgs args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; DependencyPropertyWatcher<T> source = (DependencyPropertyWatcher<T>)sender;&nbsp; &nbsp; &nbsp; &nbsp; if (source.PropertyChanged != null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; source.PropertyChanged(source.Target, args);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public void Dispose()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; this.ClearValue(ValueProperty);&nbsp; &nbsp; }}用法var watcher = new DependencyPropertyWatcher<string>(this.MyWebView, "Source");watcher.PropertyChanged += Watcher_PropertyChanged;private void Watcher_PropertyChanged(object sender, DependencyPropertyChangedEventArgs e){}

慕勒3428872

您可以使用装饰器来包装原始类并为装饰属性引发事件。
打开App,查看更多内容
随时随地看视频慕课网APP