4

I have a WPF Hyperlink which I'm trying to get the text content from.

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. I tried to get the text from FirstInline but this also doesn't give me the text.

How would I get the value "Customers" from the Hyperlink element in the above example at runtime?

codekaizen
  • 26,422
  • 7
  • 85
  • 135
Ejrr1085
  • 769
  • 1
  • 12
  • 21
  • Does using CommandParameter="Customers" work for you? Or bind to the control. http://stackoverflow.com/questions/12413985/binding-a-wpf-button-commandparameter-to-the-button-itself-in-datatemplate – kenny Oct 28 '13 at 21:41

3 Answers3

6

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;

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.

Tejas Sharma
  • 3,350
  • 20
  • 34
1

Just put a TextBlock inside and enjoy its binding flexibility .

If it's still not an option for you - use Run.Text property which is perfectly suitable solution for Hyperlink

Anatolii Gabuza
  • 6,064
  • 2
  • 35
  • 53
1

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.

crthompson
  • 15,265
  • 6
  • 55
  • 78