带有图像的 WPF 按钮样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16649913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Button style with Image
提问by Oleg Sh
I want to create a style for button with different images inside. I try to do following:
我想为里面有不同图像的按钮创建一个样式。我尝试执行以下操作:
<Style TargetType="Button"
x:Key="PaintButton">
<Setter Property="Width"
Value="40"></Setter>
<Setter Property="Height"
Value="40"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid>
<Border CornerRadius="3"
BorderThickness="2"
BorderBrush="Green">
<Image Source="{TemplateBinding Button.Content}" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
and try to use:
并尝试使用:
<Button Content="images/pen.png"
HorizontalAlignment="Left"
Style="{DynamicResource PaintButton}" />
but images is not shown. Why and how to do it correctly?
但没有显示图像。为什么以及如何正确地做到这一点?
回答by morincer
The "Image" is not a correct source for another Image. Either use BitmapImage as Button's contents or use ContentPresenter in the template.
“图像”不是另一个图像的正确来源。使用 BitmapImage 作为 Button 的内容或在模板中使用 ContentPresenter。
Option 1.
选项1。
<Button Style="{StaticResource PaintButton}">
<BitmapImage UriSource="Back_Forward.png"/>
</Button>
Option 2.
选项 2。
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid>
<Border CornerRadius="3"
BorderThickness="2"
BorderBrush="Green">
<ContentPresenter Content="{TemplateBinding Button.Content}" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
回答by Ali Alkhumairi
Please try this
请试试这个
<Style TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<StackPanel Orientation="Horizontal">
<Grid Height="30" Width="30" Background="{TemplateBinding Background}"/>
<TextBlock Text="{TemplateBinding Content}" TextAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Cursor" Value="Hand"/>
</Trigger>
</Style.Triggers>
</Style>
<Button Name="btnPrintCard" Margin="2" Content="Print Card">
<Button.Background>
<ImageBrush ImageSource="images/ic_print_black_48dp.png"/>
</Button.Background>
</Button>

