代码之家  ›  专栏  ›  技术社区  ›  hbk

依赖项财产是如何工作的?[副本]

  •  1
  • hbk  · 技术社区  · 12 年前

    试图理解此代码是如何工作的:

    创建依赖属性,

    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 回复  |  直到 12 年前
        1
  •  3
  •   rae1    12 年前

    当您创建 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 .

        2
  •  1
  •   mehdi.loa    12 年前

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

    检查 this overview

    推荐文章