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++ 开始,但我也在文本框的表单上看到它。

问:为什么?

如果我没有在主窗体中放置任何更新 TextBlock 的代码,它是自动更新还是有一些隐藏的机制?或者也许我不完全理解它是如何工作的。或者,如果它的属性有功能,可以更新表单上的数字。

4

2 回答 2

3

当您创建一个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 帖子

于 2013-10-02T19:11:02.677 回答
1

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

检查此概述

于 2013-10-02T18:35:03.270 回答