问题描述
我正在WPF应用程序中为此设置按钮样式:
<Style targettype="{x:Type Button}">
<Setter Property="ToolTipService.InitialShowDelay" Value="0"/>
<Setter Property="Height" Value="22" />
<Setter Property="Margin" Value="1" />
<Setter Property="Padding" Value="0" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate targettype="{x:Type Button}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
Padding="{TemplateBinding Padding}"
BorderThickness="1">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Margin="1 -1 1 0"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Background" Value="{StaticResource NotSelectedButton}" />
<Setter Property="Foreground" Value="{StaticResource ActiveFg}" />
<Style.Triggers>
<Trigger Property="IsMouSEOver" Value="True">
<Setter Property="Background" Value="{StaticResource Selected}" />
<Setter Property="Foreground" Value="{StaticResource SelectedFg}" />
</Trigger>
<Trigger Property="IsMouSEOver" Value="False">
<Setter Property="Background" Value="{StaticResource NotSelectedButton}" />
<Setter Property="Foreground" Value="{StaticResource ActiveFg}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Background" Value="{StaticResource NotSelectedButton}" />
<Setter Property="Foreground" Value="{StaticResource InactiveFg}" />
<!--<Setter Property="Foreground" Value="{StaticResource NotSelected}" />-->
</Trigger>
</Style.Triggers>
</Style>
但是我希望TextBlock
中的ContentPresenter
使用一种命名为TextBlock
的样式定义如下:
<Style x:Key="ButtonText" targettype="{x:Type TextBlock}">
<Setter Property="ToolTipService.InitialShowDelay" Value="0"/>
<Setter Property="Width" Value="auto" />
<Setter Property="MinWidth" Value="20" />
<Setter Property="TextAlignment" Value="Left" />
<Setter Property="Padding" Value="0 0 0 0" />
<Setter Property="Margin" Value="1 0 0 0" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
要测试此样式,只需在Button
或UserControl
中使用Window
就可以:<Button>
,并且样式定义可以放在资源字典中({ 1}}或UserControl
)。
我该怎么做?
解决方法
直接分配的临时解决方案
您可以通过为每个TextBlock
的{{1}}分配一个Content
来直接设置样式。
Button
仅支持文本作为内容
如果您确定仅将字符串作为内容放入按钮中,则可以将包含<Button>
<TextBlock Text="Test" Style="{StaticResource ButtonText}"/>
</Button>
的{{1}}分配给ContentTemplate
。这不适用于其他内容类型,因为它不会像往常一样显示它们,而只会在TextBlock
中显示它们的类型名称。
ContentPresenter
支持所有内容类型
如果您希望支持任何内容类型作为按钮的内容,则可以在TextBlock
中从上方定义数据模板。然后,只有<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Margin="1 -1 1 0">
<ContentPresenter.ContentTemplate>
<DataTemplate>
<TextBlock Style="{StaticResource ButtonText}" Text="{Binding}"/>
</DataTemplate>
</ContentPresenter.ContentTemplate>
</ContentPresenter>
是ContentPresenter.Resources
时,ContentPresenter
才会应用它。对于所有其他内容类型,它将照常工作。
Content