属性更改时引发事件

时间:2018-08-20 16:06:31

标签: c# events uwp derived-class sealed

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

谢谢。

2 个答案:

答案 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包装原始类,并为装饰的属性引发一个事件。