How can I set the text of a WPF Hyperlink via data binding?

WpfData BindingHyperlink

Wpf Problem Overview


In WPF, I want to create a hyperlink that navigates to the details of an object, and I want the text of the hyperlink to be the name of the object. Right now, I have this:

<TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">Object Name</Hyperlink></TextBlock>

But I want "Object Name" to be bound to the actual name of the object. I would like to do something like this:

<TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}" Text="{Binding Path=Name}"/></TextBlock>

However, the Hyperlink class does not have a text or content property that is suitable for data binding (that is, a dependency property).

Any ideas?

Wpf Solutions


Solution 1 - Wpf

It looks strange, but it works. We do it in about 20 different places in our app. Hyperlink implicitly constructs a <Run/> if you put text in its "content", but in .NET 3.5 <Run/> won't let you bind to it, so you've got to explicitly use a TextBlock.

<TextBlock>
    <Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">
        <TextBlock Text="{Binding Path=Name}"/>
    </Hyperlink>
</TextBlock>

Update: Note that as of .NET 4.0 the Run.Text property can now be bound:

<Run Text="{Binding Path=Name}" />

Solution 2 - Wpf

This worked for me in a "Page".

<TextBlock>
    <Hyperlink NavigateUri="{Binding Path}">
	    <TextBlock Text="{Binding Path=Path}" />
    </Hyperlink>
</TextBlock>

Solution 3 - Wpf

On Windows Store app (and Windows Phone 8.1 RT app) above example does not work, use HyperlinkButton and bind Content and NavigateUri properties as ususal.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrdeetzView Question on Stackoverflow
Solution 1 - WpfBob KingView Answer on Stackoverflow
Solution 2 - WpfJamie ClaytonView Answer on Stackoverflow
Solution 3 - WpfIvan IčinView Answer on Stackoverflow