Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 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>
question from:https://stackoverflow.com/questions/5122334/how-do-i-make-a-wpf-button-look-like-a-link

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

1 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...