【问题标题】:Raise event when property is changed更改属性时引发事件
【发布时间】:2018-08-21 10:48:30
【问题描述】:

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

谢谢。

【问题讨论】:

    标签: c# events uwp derived-class sealed


    【解决方案1】:

    属性改变时触发事件

    对于这种情况,您可以创建一个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)
    {
    
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 这不起作用,因为我无权访问 WebView 类。我不能做这样的事情:`public class MyClass: WebView´ 为了包装原来的类,我需要做这样的事情。
      • 我不确定外部代码如何通过 WebView 类或接口使用您的 webView?你可以像 WebView 类那样做 MyClass : FrameworkElement, IWebView, IWebView2, IWebView3, IWebView4, IWebView5。
      • 我无法使用 iWebView,因为我在 C# UWP 中。我唯一的网络浏览器是 WebView,我不能像你说的那样做。
      猜你喜欢
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 2011-01-29
      相关资源
      最近更新 更多