【问题标题】:How do dependency properties work? [duplicate]依赖属性如何工作? [复制]
【发布时间】:2013-10-09 06:06:22
【问题描述】:

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

创建依赖属性,

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 的代码,它是自动更新还是有一些隐藏机制?或者也许我不完全理解它是如何工作的。或者,如果它的属性有功能,可以更新表单上的数字。

【问题讨论】:

    标签: c# .net wpf dependency-properties


    【解决方案1】:

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

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

      查看this overview

      【讨论】:

      • 那么如果我使用Text="{Binding YearPublished, ElementName=_simple}" Binding 会自动为更改添加反射效果?
      • 哦,在msdn.microsoft.com/en-us/library/cc278072(v=vs.95).aspx找到When a binding is established and the data changes, the UI elements that are bound to the data can reflect changes automatically.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多