属性 更改时引发事件

Raise event when property is changed

我需要在 属性 的值更改时引发事件。在我的例子中,这是 webView.Source 被改变的时候。我无法生成派生的 class,因为 class 被标记为已密封。有什么方法可以引发事件吗?

谢谢。

您可以使用 decorator 包装原始 class 并为修饰属性引发事件。

Raise event when property is changed

对于这种情况,您可以创建一个 DependencyPropertyWatcher 来检测 DependencyProperty 更改的事件。以下是您可以直接使用的工具class。

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)
{

}