当属性值更改时,我需要引发一个事件。就我而言,这是当webView.Source更改时。我无法创建派生类,因为该类被标记为已密封。有什么办法引发事件吗?
谢谢。
答案 0 :(得分:2)
属性更改时引发事件
对于这种情况,您可以创建一个DependencyPropertyWatcher
来检测DependencyProperty
更改的事件。以下是可以直接使用的工具类。
public class DependencyPropertyWatcher<T> : DependencyObject, IDisposable
{
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register(
"Value",
typeof(object),
typeof(DependencyPropertyWatcher<T>),
new PropertyMetadata(null, OnPropertyChanged));
public event DependencyPropertyChangedEventHandler PropertyChanged;
public DependencyPropertyWatcher(DependencyObject target, string propertyPath)
{
this.Target = target;
BindingOperations.SetBinding(
this,
ValueProperty,
new Binding() { Source = target, Path = new PropertyPath(propertyPath), Mode = BindingMode.OneWay });
}
public DependencyObject Target { get; private set; }
public T Value
{
get { return (T)this.GetValue(ValueProperty); }
}
public static void OnPropertyChanged(object sender, DependencyPropertyChangedEventArgs args)
{
DependencyPropertyWatcher<T> source = (DependencyPropertyWatcher<T>)sender;
if (source.PropertyChanged != null)
{
source.PropertyChanged(source.Target, args);
}
}
public void Dispose()
{
this.ClearValue(ValueProperty);
}
}
用法
var watcher = new DependencyPropertyWatcher<string>(this.MyWebView, "Source");
watcher.PropertyChanged += Watcher_PropertyChanged;
private void Watcher_PropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
{
}
答案 1 :(得分:0)
您可以使用decorator包装原始类,并为装饰的属性引发一个事件。