試圖瞭解這個代碼是如何工作的:依賴屬性如何工作?
創建依賴屬性,
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的代碼,它會自動更新還是有一些隱藏的機制?或者,也許我不完全理解它是如何工作的。或者,如果它的屬性有功能,則更新表單上的數字。
所以,如果我使用'文本=「{Binding YearPublished,ElementName = _simple}」'綁定automaticaly添加反映效果的變化? – gbk
oh,found當綁定建立並且數據發生變化時,綁定到數據的UI元素可以自動反映更改。在http://msdn.microsoft.com/en-us/library/cc278072(v = VS.95)的.aspx – gbk