2013-01-06 57 views
1

我玩弄WPF Usercontrols,並有以下問題:爲什麼屬性初始化/分配的行爲更改後屬性是DependencyPropertyWPF Usercontrol Property Intitialization

讓我簡要說明:

考慮了UserControl類此代碼:

public partial class myUserControl : UserControl 
{ 
    private string _blabla; 
    public myUserControl() 
    { 
     InitializeComponent(); 
     _blabla = "init"; 
    } 

    //public static DependencyProperty BlaBlaProperty = DependencyProperty.Register(
    // "BlaBla", typeof(string), typeof(UserControlToolTip)); 

    public string BlaBla 
    { 
     get { return _blabla; } 
     set { _blabla = value; } 
    } 
} 

這是UserControl如何在XAML文件初始化:

<loc:myUserControl BlaBla="ddd" x:Name="myUsrCtrlName" /> 

問題我的是那行 set {_blabla = value; }僅在 DependencyProperty聲明被註釋掉時才被調用(按照此示例)。但是當 DependencyProperty行成爲程序的一部分集{_blabla = value; }行不再被系統調用。

有人可以向我解釋這種奇怪的行爲嗎?

非常感謝!

回答

1

依賴項屬性的CLR包裝器(getter和setter)只能用於調用依賴項屬性的GetValueSetValue方法。

例如

public string BlaBla 
{ 
    get { return (string)GetValue(BlaBlaProperty) } 
    set { SetValue(BlaBlaPropert, value); } 
} 

,僅此而已......
這樣做的原因是,WPF綁定引擎調用GetValueSetValue直接(例如,而不調用CLR包裝)結合時從XAML來完成。

所以你沒有看到他們被調用的原因是因爲他們真的不是,這正是你不應該添加任何邏輯到CLR獲取和設置方法的原因。

編輯
基於OP的評論 - 這裏是創建一個回調方法的一個例子,當DependencyProperty變化:

public static DependencyProperty BlaBlaProperty = 
     DependencyProperty.Register("BlaBla", typeof(string), Typeof(UserControlToolTip), 
     new FrameworkPropertyMetadata(null, OnBlachshmaPropertyChanged)); 


private static void OnBlachshmaPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
{ 
     UserControlToolTip owner = d as UserControlToolTip; 

     if (owner != null) 
     { 
      // Place logic here 
     } 
} 
+0

嗨@Blachshma,非常感謝這一點,但在這種情況下怎麼辦你*攔截* ** GetValue/SetValue **需要一個Dependance屬性,你在哪裏添加你自己的邏輯來改變值?我現在攔截在獲取/設置位置的UserControl的新值的調用,以便根據該值在控件內部採取一些操作。 – pracheta986919

+0

您可以在更改依賴項屬性時創建回調方法。添加到我的答案示例 – Blachshma

+1

非常感謝@Blachshma - 這是很好的幫助和建議!我得到了UserControl框架現在可以工作! – pracheta986919