在 WPF 中查找目标 UIElement 的标签
我有以下 XAML:
<StackPanel>
<Label Target="{Binding ElementName=txtSearch}" Content="_Search:" />
<TextBox x:Name="txtSearch" />
</StackPanel>
我有一个接受 UIElement 参数的扩展方法,如下所示:
static public class MyExtensionMethods
{
static public string GetLabelText(this UIElement element)
{
}
}
我想要在 GetLabelText 方法内部执行的所有操作是确定针对传递的 UIElement 的标签内容(如果有),并返回文本。例如,以下代码将返回“_Search:”:
string labelText = txtSearch.GetLabelText();
我听说您可以使用 AutomationPeers 来执行此操作,但到目前为止我还没有太多接触 UIAutomation 功能,并且除了空值之外似乎无法返回任何内容从我发现的任何自动化示例上对 GetLabeledBy 的调用。任何有效的答案都将是最有帮助的,但除了您已经在此处看到的内容之外,我宁愿不必在 XAML 中执行任何额外操作。
有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除了 Josh Einstein 的解决方案(如果我没记错的话,相当于简单地调用静态方法
AutomationProperties.GetLabeledBy
),我看到的此问题的唯一解决方案涉及修改 XAML slightly:通过执行此操作,您可以通过在文本框上调用
GetLabeledBy
来检索文本框的标签: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:By doing this, you can retrieve the label for the textbox by calling
GetLabeledBy
on the textbox:按照 Aviad 回复评论中的逻辑,您可以创建自己的附加属性(我会为 Label 创建它),并且当您设置属性时,它应该在标签上设置 Target 并在元素上设置 AutomationProperties.GetLabeledBy。
如果您有多个标签,则只需对其中一个标签执行此操作,然后只需在其余标签上设置 Label.Target 即可。
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.