Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
821 views
in Technique[技术] by (71.8m points)

windows - How do I make a WPF button look like a link?

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:

LinkButton in Windows 7

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

<TextBlock>                                
    <Hyperlink Command="{Binding SomeCommand, ElementName=window}" CommandParameter="{Binding}">Link
    </Hyperlink>
</TextBlock>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...