源值更改时,DataBound依赖项属性不会更新

时间:2016-05-29 05:31:18

标签: c# wpf xaml data-binding

我有一个自定义按钮,它有一个布尔属性,我试图绑定到模型的一个实例。一切似乎都是正确的,但它没有抓住房产变化......

要明确我想要发生的关系是MyControl.BooleanProperty更新以便Source.BooleanProperty更改时匹配Source.BooleanProperty

<Window
    ...
    xmlns:p="clr-namespace:FooProject.Properties"
    DataContext="{x:Static p:Settings.Default}">
    <MyControls:GlassButton        
        Pulsing="{Binding Pulse}"/>
</Window>

在应用程序设置中有一个名为“Pulse”(布尔属性)的属性。

这是我控件的相关源代码:

public class GlassButton : Button {
    #region Dependency Properties           
    public static readonly DependencyProperty
        //A whooole lot of irrelevant stuff...
        PulsingProperty = DependencyProperty.Register(
            "Pulsing", typeof(bool), typeof( GlassButton ),
            new FrameworkPropertyMetadata( false ) ),
        //Lots more irrelevant stuff

    [Category("Pulse")]
    public bool Pulsing{
        get{ return ( bool )( this.GetValue( PulsingProperty ) );
        set{
            if ( value )
                this.BeginAnimation( BackgroundProperty, this._baPulse );
            else
                this.BeginAnimation( BackgroundProperty, null );    
            this.SetValue( PulsingProperty, value );
        }
    }
    //And a pile of more irrelevant stuff.

我在Pulsing setter处设置了断点,但它们永远不会被击中......

它的行为一致,无论是在像这样的简单应用程序中,还是在真实的诚实实用的应用程序中...

为什么绑定没有服用?

1 个答案:

答案 0 :(得分:1)

您不应该依赖实例设置器来获取属性更新。因为数据绑定适用于这些实例属性设置器。要从数据绑定获取属性更新,您应在注册属性时向PropertyChangedCallback提供PropertyMetadata。像这样:

    public static readonly DependencyProperty PulsingProperty =
        DependencyProperty.Register("Pulsing", typeof (bool), typeof (GlassButton), new PropertyMetadata(false, OnPulsingPropertyChanged));

    //keep it clean
    public bool Pulsing
    {
        get
        {
            return (bool) GetValue(PulsingProperty);
        }
        set
        {
            SetValue(PulsingProperty, value);
        }
    }

    //here you get your updates
    private static void OnPulsingPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var glassButton = (GlassButton)d;
        var newPulsingValue = (bool)e.NewValue;
        if (newPulsingValue)
            glassButton.BeginAnimation( BackgroundProperty, glassButton._baPulse );
        else
            glassButton.BeginAnimation( BackgroundProperty, null );
    }