I want to use buttons in WPF that are styled like links. Microsoft does this (seemingly inconsistently) in its Windows dialog boxes.
They look like blue text. And change color and underline when the mouse cursor hovers over.
Example:
I got it working. (thanks to Christian, Anderson Imes, and MichaC) But, I had to put a TextBlock
inside my button.
How can I improve my style—to make it work without requiring the TextBlock inside my Button?
Usage XAML
<Button Style="{StaticResource HyperlinkLikeButton}">
<TextBlock>Edit</TextBlock>
</Button>
Style XAML
<Style x:Key="HyperlinkLikeButton" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HotTrackBrushKey}}" />
<Setter Property="Cursor" Value="Hand" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<ControlTemplate.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextDecorations" Value="Underline" />
</Style>
</ControlTemplate.Resources>
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
I think the trouble is that button is a content control, but the link style works only with text as a content. This is the reason the code you have is designed that way. I think we can work in the control template by specifying a textblock instead of content presenter, but what property bind to it ? So my proposal is: subclass the button and declare a dependency property of type string and use that property to bind the text in the ControlTemplate.
Using the following style or template does not require you to use the TextBlock element:
Usage XAML
or
or you can use the template directly
Unless I'm missing something, couldn't you get away with styling the
TextBlock
, if you're applying the styles inline as opposed to globally, anyway? For instance:And so:
To enable clicking, simply use the
MouseUp
event.Do you know there is a Hyperlink class/tag? It looks like a hyperlink and can work also as button (can use URI and/or command and/or click event).
EDIT:
Example of usage:
I'm a little late for the party but ...
The simplest and cleanest approach IMO :