简体   繁体   English

如何在 WPF 中从 C# 获取超链接文本?

[英]How to get HyperLink Text from C# in WPF?

I have a WPF Hyperlink which I'm trying to get the text content from.我有一个 WPF Hyperlink ,我试图从中获取文本内容。

For example:例如:

<Hyperlink Command="{Binding CustomersCommand}" Name="HLCustomers">
    Customers
</Hyperlink>

This is not possible using the usual manner of accessing a Text property or using VisualTreeHelper to get some child text element, since Hyperlink is not a visual element.使用访问Text属性或使用VisualTreeHelper获取某些子文本元素的通常方式是不可能的,因为Hyperlink不是可视元素。 I tried to get the text from FirstInline but this also doesn't give me the text.我试图从FirstInline获取文本,但这也没有给我文本。

How would I get the value "Customers" from the Hyperlink element in the above example at runtime?如何在运行时从上述示例中的Hyperlink元素中获取值“Customers”?

If you really need to get the text contained within the Hyperlink , you can dig in to the Inlines property it exposes and get it.如果你真的需要获取包含在Hyperlink的文本,你可以深入到它公开的Inlines属性并获取它。

var run = HLCustomers.Inlines.FirstOrDefault() as Run;
string text = run == null ? string.Empty : run.Text;

Note, that this will only work if the first inline in your Hyperlink is indeed a Run .请注意,这仅在Hyperlink的第一个内联确实是Run时才有效。 You can finagle with this example for more complex cases.对于更复杂的情况,您可以使用此示例进行处理。

Just put a TextBlock inside and enjoy its binding flexibility .只需在里面放一个TextBlock享受其绑定灵活性。

If it's still not an option for you - use Run.Text property which is perfectly suitable solution for Hyperlink如果它仍然不是您的选择 - 使用Run.Text属性,这是非常适合Hyperlink解决方案

Is adding a text block a problem?添加文本块有问题吗?

<Hyperlink Command="{Binding CustomersCommand}" Name="HLCustomers">
    <TextBlock Name="HLCustomersContent">
        Customers
    </TextBlock>
</Hyperlink>

Then you could just reference it as:然后你可以将它引用为:

var text = HLCustomersContent.Text;

The .Text property on a WPF Hyperlink object is set to internal, so unless you overrode it and exposed the text property, it is not as easily as accessible as you would might like. WPF 超链接对象上的.Text属性设置为 internal,因此除非您覆盖它并公开 text 属性,否则它不会像您希望的那样容易访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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