简体   繁体   中英

How do I programmatically read the value of an attached dependency property?

So I have a Button with an AutomationId (used by Microsoft UI Automation) like so:

<Button Name="myButton" AutomationId="myButtonAutomationID" 

Programmatically, I have the button (myButton) in code, how do I get the value of the 'AutomationId' property attached to that button?

DependencyObject.GetValue should do the job:

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

Fundamentally, just as you would with any other DependencyProperty ; the ordinary properties on your object serve (or should serve) as simple wrappers around DependencyObject.GetValue and .SetValue , so all you need to do is call GetValue yourself and pass in your static readonly instance of your attached DependencyProperty :

var value = myButton.GetValue(yourDependencyProperty);
var automationId = AutomationProperties.GetAutomationId(myButton);

As is standard for dependency properties, this wrapper method will do the job of calling DependencyObject.GetValue for you, and casting the value to the correct type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM