C# 依赖属性是如何工作的?
试图了解此代码的工作原理: 创建依赖项属性C# 依赖属性是如何工作的?,c#,.net,wpf,dependency-properties,C#,.net,Wpf,Dependency Properties,试图了解此代码的工作原理: 创建依赖项属性 public int YearPublished { get { return (int)GetValue(YearPublishedProperty); } set { SetValue(YearPublishedProperty, value); } } public static readonly DependencyProperty YearPublishedProperty = DependencyProperty.
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>
它起作用了。每次按下按钮时,数字都必须从PropertyMetadata(从2000++)更改,但我在文本框的表单上也看到了它
问题:为什么
如果我没有在主窗体中添加任何更新TextBlock的代码,它是自动更新的还是有一些隐藏的机制?或者我不完全理解它是如何工作的。或者,如果其属性包含更新表单上数字的功能。如果绑定具有正确的设置,并且数据提供了正确的通知,则当数据更改其值时,绑定到数据的元素会自动反映更改
检查如果绑定具有正确的设置并且数据提供了正确的通知,则当数据更改其值时,绑定到数据的元素会自动反映更改
创建
依赖属性时,请选中
DependencyProperty.Register(
"YearPublished",
typeof(int),
typeof(SimpleControl),
new PropertyMetadata(2000));
基于YearPublished属性,您基本上是在DependencyProperty框架中注册它,每次读取或写入该属性时,它都会通知所有订阅者已发生的事件。您可以通过指定属性名称(即“YearPublished”
、属性类型、属性所在控件的类型以及在本例中的初始值2000
)来注册它
通过将其绑定到文本块
<TextBlock Text="{Binding YearPublished, ElementName=_simple}" />
您正在让文本块知道属性何时更改,以便它可以自行更新。当YearPublished
属性更改时,它会将此更改通知文本块,然后文本块会检索更新的值并用它更新其text
属性
虽然这是一个非常高级的视图,但足以正确使用它。要进一步了解内部结构,请查看此项。当您创建DependencyProperty时
DependencyProperty.Register(
"YearPublished",
typeof(int),
typeof(SimpleControl),
new PropertyMetadata(2000));
基于YearPublished属性,您基本上是在DependencyProperty框架中注册它,每次读取或写入该属性时,它都会通知所有订阅者已发生的事件。您可以通过指定属性名称(即“YearPublished”
、属性类型、属性所在控件的类型以及在本例中的初始值2000
)来注册它
通过将其绑定到文本块
<TextBlock Text="{Binding YearPublished, ElementName=_simple}" />
您正在让文本块知道属性何时更改,以便它可以自行更新。当YearPublished
属性更改时,它会将此更改通知文本块,然后文本块会检索更新的值并用它更新其text
属性
虽然这是一个非常高级的视图,但足以正确使用它。为了进一步理解内部结构,请看一看。因此,如果我使用Text=“{Binding YearPublished,ElementName=\u simple}”
Binding automatically add reflect effect on changes?噢,在建立绑定和数据更改时发现,绑定到数据的UI元素可以自动反映更改。
因此,如果我使用Text=“{Binding YearPublished,ElementName=_simple}”
绑定自动添加对更改的反映效果?哦,当绑定建立且数据更改时,发现,绑定到数据的UI元素可以自动反映更改。
at