Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a public event for a dependency property?

In the code below you can see what I'm trying to do, but it doesn't work. I want an event that I can attach to outside of my user control and fires whenever the dependency property changes.

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value"
        , typeof(Double)
        , typeof(ucSlider)
        , new PropertyMetadata(50d, new PropertyChangedCallback(OnValueChanged)));

    public Double Value
    {
        get { return (Double)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    public event PropertyChangedCallback OnValueChanged;
like image 969
descf Avatar asked Nov 17 '25 05:11

descf


1 Answers

Dependency properties are static, but your event is related with the instance of the class. So you need an intermediate method between the static property and the event of instance.

In this example I pass the static method OnValuePropertyChanged as a callback parameter and inside it I raise the event:

public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register("Value"
    , typeof(Double)
    , typeof(ucSlider)
    , new PropertyMetadata(50d, new PropertyChangedCallback(OnValuePropertyChanged)));

public Double Value
{
    get { return (Double)GetValue(ValueProperty); }
    set { SetValue(ValueProperty, value); }
}

public static void OnValuePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    var sl = sender as ucSlider;
    if (sl != null)
        sl.RaiseValueChangedEvent(e);
}

private void RaiseValueChangedEvent(DependencyPropertyChangedEventArgs e)
{
    if(this.OnValueChanged != null)
        this.OnValueChanged(this, e);
}

public event PropertyChangedCallback OnValueChanged;
like image 65
vortexwolf Avatar answered Nov 18 '25 21:11

vortexwolf