简体   繁体   English

属性更改时引发事件

[英]Raise event when property is changed

I need to raise an event when the value of the property is changed. 当属性的值更改时,我需要引发一个事件。 In my case this is when webView.Source is changed. 就我而言,这是当webView.Source更改时。 I can't make a derived class because the class is marked as sealed. 我无法创建派生类,因为该类被标记为已密封。 Is there any way to raise an event ? 有什么办法引发一个事件吗?

Thank you. 谢谢。

Raise event when property is changed 属性更改时引发事件

For this scenario, you could create a DependencyPropertyWatcher to detect DependencyProperty changed event. 对于这种情况,您可以创建一个DependencyPropertyWatcher来检测DependencyProperty更改的事件。 The follow is tool class that you could use directly. 以下是可以直接使用的工具类。

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);
    }
}

Usage 用法

var watcher = new DependencyPropertyWatcher<string>(this.MyWebView, "Source");
watcher.PropertyChanged += Watcher_PropertyChanged;

private void Watcher_PropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
{

}

您可以使用装饰器包装原始类,并为装饰的属性引发一个事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM