依赖属性如何工作?

时间:2013-10-02 18:21:56

标签: c# .net wpf dependency-properties

试图了解此代码的工作原理:

创建依赖属性,

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 个答案:

答案 0 :(得分:2)

创建DependencyProperty时,

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

基于YearPublished属性,您基本上使用DependencyProperty框架注册它,每次读取或写入属性时,它都会通知所有订阅者已发生的事件。您可以通过指定属性的名称来注册它,即"YearPublished",属性类型,属性所在的控件的类型,在本例中为2000的初始值。

通过将其绑定到TextBlock

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

当属性发生更改时,您会让文本块知道,以便它可以自行更新。当YearPublished属性发生更改时,它会通知文本块此更改,后者会检索更新后的值并使用它更新其Text属性。

这是一个非常高级别的视图,但足以正确使用它。要进一步了解内部结构,请查看此MSDN post

答案 1 :(得分:1)

如果绑定具有正确的设置并且数据提供了正确的通知,那么,当数据更改其值时,绑定到数据的元素会自动更改。

检查this overview

相关问题