2016-05-29 120 views
0

我有一個自定義按鈕具有布爾屬性,我試圖綁定到模型的實例。一切似乎是正確的,但它並沒有趕上財產的變化...DataBound依賴項屬性不會更新源值更改

要清除我想要發生的關係是MyControl.BooleanProperty更新匹配Source.BooleanPropertySource.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二傳手斷點,但他們永遠不會打......

它的一貫表現,無論是在bare-像這樣的骨骼應用程序,或在一個實際的誠實善良真正的應用程序...

爲什麼綁定沒有采取?

回答

1

您不應該依賴實例setter來獲取屬性更新。因爲數據綁定在這些實例屬性設置器周圍起作用。要從數據綁定中獲取屬性更新,您應在註冊屬性時提供PropertyChangedCallbackPropertyMetadata。像這樣:

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

嗯......這很有趣我必須看看,但是,這是有道理的......謝謝。 – Will

+0

這就是問題所在。非常感謝(我討厭自己)。 – Will

相關問題