Find the Label for a Targeted UIElement in WPF
I have the following XAML:
<StackPanel>
<Label Target="{Binding ElementName=txtSearch}" Content="_Search:" />
<TextBox x:Name="txtSearch" />
</StackPanel>
I have an extension method that accepts a UIElement parameter like so:
static public class MyExtensionMethods
{
static public string GetLabelText(this UIElement element)
{
}
}
All I want to do inside of the GetLabelText method is to determine the Content of the Label (if there is one) that is targeting the passed UIElement, and return the text. For example, the following code would return "_Search:":
string labelText = txtSearch.GetLabelText();
I have heard that you can do this using AutomationPeers, but I have not had much exposure to the UIAutomation features as of yet and can't seem to get anything back but null values from calls 开发者_如何学运维to GetLabeledBy on any of the Automation examples I've found. Any answer that works would be most helpful, but I'd prefer to not have to do anything extra in my XAML except what you already see here.
Any ideas?
Apart from the solution by Josh Einstein, which is, if I'm not mistaken, equivalent to simply calling the static method AutomationProperties.GetLabeledBy
, the only solution I see to this problem involves modifying the XAML slightly:
<StackPanel>
<Label x:Name="lblSearch" Target="{Binding ElementName=txtSearch}" Content="_Search:" />
<TextBox x:Name="txtSearch" AutomationProperties.LabeledBy="{Binding ElementName=lblSearch}"/>
</StackPanel>
By doing this, you can retrieve the label for the textbox by calling GetLabeledBy
on the textbox:
var labeledBy = AutomationProperties.GetLabeledBy(txtSearch);
Assert(labeledBy == lblSearch);
Following the logic in the comment of Aviad's reply you could make your own attached property (I would make it for Label) and when you set the property it should set the Target on the label and AutomationProperties.GetLabeledBy on the element.
And if you have several labels only do this with one of them and simply set Label.Target on the rest.
精彩评论