使用图像+文本设计 WPF 按钮样式 [英] Styling a WPF Button with Image+Text
问题描述
在我的 C#/WPF/.NET 4.5 应用程序中,我有一些带有图像的按钮,我以以下方式实现:
In my C#/WPF/.NET 4.5 application I have buttons with images that I implemented in the following fashion:
<Button Style="{StaticResource BigButton}">
<StackPanel>
<Image Source="Images/Buttons/bt_big_save.png" />
<TextBlock>save</TextBlock>
</StackPanel>
</Button>
我有一个资源字典 UIStyles.xaml,我在其中声明了以下内容:
I have a resource dictionary UIStyles.xaml in which I declare the following:
<Style TargetType="Button" x:Key="BigButton">
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Height" Value="80" />
<Setter Property="Width" Value="80" />
<Setter Property="Foreground" Value="White" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="border"
CornerRadius="5"
Background="#FF415360">
<ContentPresenter x:Name="ButtonContentPresenter"
VerticalAlignment="Center"
HorizontalAlignment="Center">
<ContentPresenter.Resources>
<Style TargetType="TextBlock">
<Setter Property="TextAlignment" Value="Center" />
</Style>
<Style TargetType="Image">
<Setter Property="Width" Value="10" />
<Setter Property="Margin" Value="10" />
</Style>
</ContentPresenter.Resources>
</ContentPresenter>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
光标、高度、边框等属性工作正常,但我无法设置 TextBlock
和 Image
的样式.
The cursor, height, border etc. properties work fine, but I can't style the TextBlock
and the Image
.
具体来说,需要看起来像这样:
Specifically, what needs to look like this:
最终看起来像这样(不考虑色差):
Ends up looking like this (disregarding the color difference):
我见过类似的问题之前问过但解决方案使用了不同的方法(我不想创建自定义用户控件,除此之外我的所有需求都包含在当前代码中,重写将是一件麻烦事).我只需要修复我的 Style
以便 TextBlock
居中并且 Image
居中并变小.
I've seen similar questions asked before but the solutions used different approaches (I don't want to create a custom User Control, all of my needs except this one are covered in the present code and re-writing will be a nuisance). I merely need to fix my Style
so that the TextBlock
is centered and the Image
is centered and made smaller.
如何重新编写 Style
以纠正按钮的外观?
How do I re-write the Style
to correct the look of my buttons?
推荐答案
解决您的问题的方法可能是将您的 Image 和 TextBlock 样式移动到 ControlTemplate 的 Resource 部分.我不确定为什么,但我相信如果样式是内容展示者资源的一部分,它们就不在范围内.
The solution to your problem may be to move your Image and TextBlock styles to the ControlTemplate's Resource section. I'm not sure why, but I believe the styles aren't in scope if they are part of the content presenter's resources.
这篇关于使用图像+文本设计 WPF 按钮样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!