链接button在wpf
我如何使Button看起来像LinkButton,而我不想使用超链接…!
有什么build议么
如果你不想要任何正常的Button风格,只想看起来像超链接的东西,你可以从这开始
<Button Margin="5" Content="Test" Cursor="Hand"> <Button.Template> <ControlTemplate TargetType="Button"> <TextBlock TextDecorations="Underline"> <ContentPresenter /> </TextBlock> </ControlTemplate> </Button.Template> <Button.Style> <Style TargetType="Button"> <Setter Property="Foreground" Value="Blue" /> <Style.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Foreground" Value="Red" /> </Trigger> </Style.Triggers> </Style> </Button.Style> </Button>
这跟风格一样:
<Style x:Key="LinkButton" TargetType="Button"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <TextBlock TextDecorations="Underline"> <ContentPresenter /></TextBlock> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Foreground" Value="Blue" /> <Style.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Foreground" Value="Red" /> </Trigger> </Style.Triggers> </Style>
你可以像这样使用它:
<Button Style="{StaticResource LinkButton}" Content="Clicky" />
这里是MichaC的build议作为一种Style
实现,你可以在任何button上重用:
<Style x:Key="LinkButton" TargetType="Button"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <TextBlock TextDecorations="Underline"> <ContentPresenter /> </TextBlock> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Foreground" Value="Blue" /> <Setter Property="Cursor" Value="Hand" /> <Style.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Foreground" Value="Red" /> </Trigger> </Style.Triggers> </Style>
<Style x:Key="LinkButton" TargetType="Button" BasedOn="{StaticResource ResourceKey={x:Type Button}}" > <Setter Property="Width" Value="Auto"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <ContentPresenter Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" VerticalAlignment="Center" > <ContentPresenter.Resources> <Style TargetType="{x:Type TextBlock}"> <Setter Property="TextDecorations" Value="Underline" /> </Style> </ContentPresenter.Resources> </ContentPresenter> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Foreground" Value="Blue" /> <Setter Property="Cursor" Value="Hand" /> <Style.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Foreground" Value="Red" /> </Trigger> </Style.Triggers> </Style>
MichaC和Anderson的版本放置下划线有一点错误,这是一个更新的版本,将只添加一个底线到ContentPresenter
内的任何TextBlock
。
最简单的方法(我在我的应用程序中这样做):
<TextBlock Name="..." Text="..." Cursor="Hand" Foreground="Blue" TextDecorations="Underline" MouseLeftButtonUp=..." />
您可以完全控制TextDecoration,例如更改笔样式或偏移量。 看看这个链接了解更多: http : //msdn.microsoft.com/en-us/library/system.windows.textdecorations.underline.aspx
使用Hyperlink
另一个解决scheme是放在TextBlock
里面。
<TextBlock> <Hyperlink Click="..."> <TextBlock Text="Link text" /> </Hyperlink> </TextBlock>
为什么你不想使用超链接?
<Button> <Hyperlink> </Button>