2010-12-06 129 views
7

我有一個自定義依賴屬性定義,像這樣:WPF依賴項屬性不工作

public static readonly DependencyProperty MyDependencyProperty = 
DependencyProperty.Register(
"MyCustomProperty", typeof(string), typeof(MyClass)); 

    private string _myProperty; 
    public string MyCustomProperty 
    { 
     get { return (string)GetValue(MyDependencyProperty); } 
     set 
     { 
      SetValue(MyDependencyProperty, value); 
     } 
    } 

現在我嘗試設置該屬性在XAML

<controls:TargetCatalogControl MyCustomProperty="Boo" /> 

但在DependencyObject的二傳手從來沒有被擊中!雖然它會在我將屬性更改爲常規屬性時使用,而不是Dep支持方案

回答

15

試試這個..

public string MyCustomProperty 
    { 
     get 
     { 
      return (string)GetValue(MyCustomPropertyProperty); 
     } 
     set 
     { 
      SetValue(MyCustomPropertyProperty, value); 
     } 
    } 

    // Using a DependencyProperty as the backing store for MyCustomProperty. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty MyCustomPropertyProperty = 
     DependencyProperty.Register("MyCustomProperty", typeof(string), typeof(TargetCatalogControl), new UIPropertyMetadata(MyPropertyChangedHandler)); 


    public static void MyPropertyChangedHandler(DependencyObject sender, DependencyPropertyChangedEventArgs e) 
    { 
     // Get instance of current control from sender 
     // and property value from e.NewValue 

     // Set public property on TaregtCatalogControl, e.g. 
     ((TargetCatalogControl)sender).LabelText = e.NewValue.ToString(); 
    } 

    // Example public property of control 
    public string LabelText 
    { 
     get { return label1.Content.ToString(); } 
     set { label1.Content = value; } 
    } 
2

它不會,除非您手動調用它。有一個屬性更改的處理程序可以添加到DependancyProperty構造函數調用中,以便在屬性更改時通知它。

調用此構造:

http://msdn.microsoft.com/en-us/library/ms597502.aspx

與此構造函數創建一個實例PropertyMetadata:

http://msdn.microsoft.com/en-us/library/ms557327.aspx

編輯:另外,你是不是正確地實現扶養財產。您的getset應分別使用GetValueSetValue,並且您不應該有一個類成員來存儲該值。 DP的成員名稱也應該是{PropertyName}Property,例如MyCustomPropertyProperty如果get/set和註冊的屬性名稱是MyCustomProperty。有關更多信息,請參閱http://msdn.microsoft.com/en-us/library/ms753358.aspx

希望有所幫助。

+0

嗨基恩,在你的第一個鏈接沒有「構造函數」來調用,它解釋了「DependencyProperty.Register方法」,這是我使用的。你發佈了錯誤的鏈接嗎?在你的第二個鏈接是關於PropertyChangedCallback,這是否解決了我的問題?我的副總裁安裝員沒有被調用,這是我遇到的問題! – Bob 2010-12-06 16:59:40

+0

我的意思是註冊方法,而不是構造函數。不應該調用setter,您正在使用DP,並且必須遵循提供的鏈接中描述的模式。 WPF不會調用你的setter,它會使用SetValue:你必須提供一個PropertyMetadata對象,當它改變你的值時,它將被WPF調用。 – 2010-12-16 11:24:30

1

也許你正在使用MVVM,並重寫你瀏覽的DataContext的?

如果這樣做,則更改MyCustomProperty的事件將在原始 DataContext上引發,而不是在新的ViewModel上引發。