C# 如何以编程方式读取附加的依赖项属性的值?

C# 如何以编程方式读取附加的依赖项属性的值?,c#,wpf,dependency-properties,C#,Wpf,Dependency Properties,因此,我有一个带有AutomationId(由Microsoft UI Automation使用)的按钮,如下所示: 应完成以下工作: string automationId = (string)myButton.GetValue(AutomationProperties.AutomationIdProperty); 基本上,就像您处理任何其他DependencyProperty一样;对象上的普通属性充当(或应该充当)围绕DependencyObject.GetValue和.SetV

因此,我有一个带有AutomationId(由Microsoft UI Automation使用)的按钮,如下所示:

应完成以下工作:

string automationId = 
    (string)myButton.GetValue(AutomationProperties.AutomationIdProperty);

基本上,就像您处理任何其他
DependencyProperty
一样;对象上的普通属性充当(或应该充当)围绕
DependencyObject.GetValue
.SetValue
的简单包装器,因此您只需自己调用
GetValue
并传入附加
DependencyProperty
静态只读
实例:

var value = myButton.GetValue(yourDependencyProperty);

作为依赖项属性的标准,此包装器方法将为您调用
DependencyObject.GetValue
,并将值强制转换为正确的类型。

可以避免强制转换,只需调用
AutomationProperties.GetAutomationId(myButton)
var value = myButton.GetValue(yourDependencyProperty);
var automationId = AutomationProperties.GetAutomationId(myButton);