Search code examples
c#eventsuwpderived-classsealed

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. I can't make a derived class because the class is marked as sealed. Is there any way to raise an event ?

Thank you.


Solution

  • Raise event when property is changed

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

    Usage

    var watcher = new DependencyPropertyWatcher<string>(this.MyWebView, "Source");
    watcher.PropertyChanged += Watcher_PropertyChanged;
    
    private void Watcher_PropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
    
    }