tags:

views:

88

answers:

1

Hello,

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?

A: 

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);
Aviad P.
I figured that is what I would have to do to use the UIAutomation features available to me, but I need to do a lot more reading on the subject because it still doesn't make sense why I have to specify AutomationProperties dependency properties in my XAML. I'm missing how a feature like this could be useful if it doesn't work automatically. Shrug. Thanks for your input though. Much appreciated.
Lusid
I guess it is a matter of sematics, having a label sit next to another control in XAML or in memory is not enough to suggest a `labeled-by` relationship between them - It has to be set explicitly. And if you're going to suggest reversing the `Target` relationship, remember it is a many-to-one relationship, so you'd have to deal with a collection of labels. The `labeled-by` relationship designates only a single label for the control. Of course, then you could say, hey how can one label be the label of several controls? I like having a discussion with myself...
Aviad P.