如何在 WPF 中从 C# 获取超链接文本? [英] How to get HyperLink Text from C# in WPF?
问题描述
我有一个 WPF Hyperlink
,我试图从中获取文本内容.
I have a WPF Hyperlink
which I'm trying to get the text content from.
例如:
<Hyperlink Command="{Binding CustomersCommand}" Name="HLCustomers">
Customers
</Hyperlink>
使用通常的方式访问 Text
属性或使用 VisualTreeHelper
获取一些子文本元素是不可能的,因为 Hyperlink
是不是视觉元素.我试图从 FirstInline
获取文本,但这也没有给我文本.
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. I tried to get the text from FirstInline
but this also doesn't give me the text.
如何在运行时从上述示例中的 Hyperlink
元素中获取值Customers"?
How would I get the value "Customers" from the Hyperlink
element in the above example at runtime?
推荐答案
如果您确实需要获取 Hyperlink
中包含的文本,您可以深入到 Inlines
它公开并获取它的属性.
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.
var run = HLCustomers.Inlines.FirstOrDefault() as Run;
string text = run == null ? string.Empty : run.Text;
请注意,这仅在 Hyperlink
中的第一个内联确实是 Run
时才有效.对于更复杂的情况,您可以使用此示例进行处理.
Note, that this will only work if the first inline in your Hyperlink
is indeed a Run
. You can finagle with this example for more complex cases.
这篇关于如何在 WPF 中从 C# 获取超链接文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!