如何在WPF中应用样式到按钮
本文关键字:样式 按钮 应用 WPF | 更新日期: 2023-09-27 18:05:08
我正试图应用样式按钮,我们如何才能实现这一点?
下面是我的示例XAML,但它不能工作
<Grid>
<Button Width="150" Height="50">
<Button.Template>
<ControlTemplate>
<Label Content="Helllo"/>
</ControlTemplate>
</Button.Template>
<Button.Style>
<Style TargetType="Button">
<Setter Property="Background" Value="Green"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="AliceBlue"/>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</Grid>
你的样式设置没有问题。
ControlTemplate被覆盖,所以你需要模板绑定Label的背景属性与按钮的背景属性。
你应该这样做:
<ControlTemplate>
<Label Content="Helllo" Background="{TemplateBinding Background}"/>
</ControlTemplate>
使用ContentTemplate代替ControlTemplate,它将使您的按钮事件保持其样式。参考 ContentTemplate和Template的区别
<Button Width="150" Height="50">
<Button.ContentTemplate>
<DataTemplate>
<Label Content="Helllo"/>
</DataTemplate>
</Button.ContentTemplate>
<Button.Style>
<Style TargetType="Button">
<Setter Property="Background" Value="Green"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="AliceBlue"/>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
当您重写控件模板时,您需要为该控件实现整个默认控件模板。链接:http://msdn.microsoft.com/en-us/library/ms753328%28v=vs.110%29.aspx
我提供的示例代码是为我工作很好:
<Grid>
<Grid.Resources>
<SolidColorBrush x:Key="ControlBackground_MouseOver" Color="AliceBlue"/>
</Grid.Resources>
<Button Width="150" Height="50" Content="Hello" >
<Button.Template>
<ControlTemplate TargetType="Button">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="Background" Duration="0:0:0">
<DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{StaticResource ControlBackground_MouseOver}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border x:Name="Border"
BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
/>
<ContentControl x:Name="ContentElement"
IsTabStop="False"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
Foreground="{TemplateBinding Foreground}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
</ContentControl>
<Border
BorderThickness="1"
Opacity="0"
x:Name="FocusState"
/>
</Grid>
</ControlTemplate>
</Button.Template>
<Button.Style>
<Style TargetType="Button">
<Setter Property="Background" Value="Green"/>
</Style>
</Button.Style>
</Button>
</Grid>
如果你只想在按钮上显示文本,你可以使用按钮的content属性。如果这就是你要找的,请告诉我。谢谢。