views:

9699

answers:

3

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?

+26  A: 

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 it's "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}" />
Bob King
So, does that mean the content property of a Hyperlink is the Inlines collection?
Mal Ross
A: 

You really want a button object where you set the content property to be a hyperlink. Remember in WPF, the class you use is based on what it does, not what it looks like.

A button issues a command and has all the properties you want. It also allows you to style it however by simply saying:

<Button Command="myCommand" Style="{StaticResource HyperlinkStyle}" Content="{Binding}" />

Just because the default form for button is a traditional button, doesn't mean it has to look that way. Traditionally this is called a LinkButton.

Orion Adrian
I don't actually know what using a <Button/> would buy you other than a heavier-weight object.
Bob King
Button isn't that much heavier than Hyperlink and it was designed to do what you're looking for.
Orion Adrian
That's incredibly heavy-weight (a Button has a much larger memory footprint that two textblocks), and still doesn't solve the original problem of not being able to make the hyperlink's text be data-bound.
Bob King
@Bob King, the styling of the button can be a hyperlink. The content can be a hyperlink.
Orion Adrian
A: 

This worked for me in a "Page".

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