2013-10-02 26 views
1

試圖瞭解這個代碼是如何工作的:依賴屬性如何工作?

創建依賴屬性,

public int YearPublished 
{ 
    get { return (int)GetValue(YearPublishedProperty); } 
    set { SetValue(YearPublishedProperty, value); } 
} 

public static readonly DependencyProperty YearPublishedProperty = 
    DependencyProperty.Register(
     "YearPublished", 
     typeof(int), 
     typeof(SimpleControl), 
     new PropertyMetadata(2000)); 

然後在窗體中使用它,

<xmlns:local="clr-namespace:WpfApplication1" 
    Title="MainWindow" Height="350" Width="525"> 
<StackPanel> 
    <local:SimpleControl x:Name="_simple" /> 
    <TextBlock Text="{Binding YearPublished, ElementName=_simple}" 
       FontSize="30" 
       TextAlignment="Center" /> 
    <Button Content="Change Value" 
      FontSize="20" 
      Click="Button_Click_1"/> 
</StackPanel> 

那麼對於Button_Click_1做,

private void Button_Click_1(object sender, RoutedEventArgs e) 
{ 
    _simple.YearPublished++; 
} 

它的工作原理。每次按下按鈕時,數字必須從PropertyMetadata(從2000 ++)更改,但我也在textBox中的窗體中看到它。

問:爲什麼?

如果我沒有在主窗體中放置任何更新TextBlock的代碼,它會自動更新還是有一些隱藏的機制?或者,也許我不完全理解它是如何工作的。或者,如果它的屬性有功能,則更新表單上的數字。

回答

2

當你創建一個DependencyProperty

DependencyProperty.Register(
    "YearPublished", 
    typeof(int), 
    typeof(SimpleControl), 
    new PropertyMetadata(2000)); 

基礎上,YearPublished財產,你基本上是在一個方式的DependencyProperty框架註冊它,每一次房地產讀取或寫到,它通知所有訂閱者已發生的事件。您可以通過指定屬性的名稱(即"YearPublished"),屬性類型,屬性所在的控件類型以及在此情況下的初始值2000進行註冊。

通過將其綁定到TextBlock

<TextBlock Text="{Binding YearPublished, ElementName=_simple}" /> 

你讓文本塊知道什麼時候屬性的變化,因此它可以自行更新。當YearPublished屬性發生更改時,它將通知此更改的文本塊,該更改依次檢索更新的值並使用它更新其屬性。

雖然這是一個很高層次的視圖,但足以正確使用它。爲了進一步瞭解內部結構,請看這個MSDN post

1

如果綁定具有正確的設置並且數據提供了正確的通知,那麼當數據更改其值時,綁定到數據的元素會自動反映更改。

檢查this overview

+0

所以,如果我使用'文本=「{Binding YearPublished,ElementName = _simple}」'綁定automaticaly添加反映效果的變化? – gbk

+0

oh,found當綁定建立並且數據發生變化時,綁定到數據的UI元素可以自動反映更改。在http://msdn.microsoft.com/en-us/library/cc278072(v = VS.95)的.aspx – gbk