属性更改时引发事件

属性更改时引发事件

本文介绍了属性更改时引发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to raise an event when the value of the property is changed. In my case this is when webView.Source is changed. I can't make a derived class because the class is marked as sealed. Is there any way to raise an event ?

谢谢.

推荐答案

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

For this scenario, you could create a DependencyPropertyWatcher to detect DependencyProperty changed event. 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);
    }
}

用法

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

private void Watcher_PropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
{

}

这篇关于属性更改时引发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 08:48