开发者

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

开发者 https://www.devze.com 2023-02-20 02:39 出处:网络
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.

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 stat开发者_运维问答ic 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;


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消