在WPF中,我们正在创建自定义控件,这些控件继承自完全从头开始绘制xaml图形的按钮。我们在整个按钮xaml周围有一个边框,我们想在触发器中将MouseOver = True时用它作为更新背景的位置。我们需要知道的是,当鼠标悬停在梯形图上时,我们如何使用渐变更新此按钮的边框背景?
答案 0 :(得分:3)
在ControlTemplate
中,给Border
一个Name
,然后您可以在触发器中引用其可视树的那一部分。以下是重新定义普通Button
:
<Style
TargetType="{x:Type Button}">
<Setter
Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Name="customBorder"
CornerRadius="5"
BorderThickness="1"
BorderBrush="Black"
Background="{StaticResource normalButtonBG}">
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger
Property="IsMouseOver"
Value="True">
<Setter
TargetName="customBorder"
Property="Background"
Value="{StaticResource hoverButtonBG}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
如果这没有用,我们需要了解更多,可能会看到你自己的XAML。你的描述并没有让我清楚你的实际视觉树是什么。
答案 1 :(得分:0)
你想要添加这样的触发器......
制作这样的风格:
<Style x:Key="ButtonTemplate"
TargetType="{x:Type Button}">
<Setter Property="Foreground"
Value="{StaticResource ButtonForeground}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate
TargetType="{x:Type Button}">
<Grid
SnapsToDevicePixels="True"
Margin="0,0,0,0">
<Border Height="20"
x:Name="ButtonBorder"
BorderBrush="{DynamicResource BlackBorderBrush}">
<TextBlock x:Name="button"
TextWrapping="Wrap"
Text="{Binding Path=Content, RelativeSource={RelativeSource TemplatedParent}}"
SnapsToDevicePixels="True"
Foreground="#FFFFFFFF"
Margin="6,0,0,0"
VerticalAlignment="Center"/>
</Border>
</Grid>
<ControlTemplate.Triggers>
<!-- Disabled -->
<Trigger Property="IsMouseOver"
Value="True">
<Setter TargetName="ButtonBorder"
Property="Background"
Value="{DynamicResource ButtonBackgroundMouseOver}" />
<Setter TargetName="ButtonBorder"
Property="BorderBrush"
Value="{DynamicResource ButtonBorderMouseOver}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
然后为渐变添加一些资源,如下所示:
<LinearGradientBrush x:Key="ButtonBackgroundMouseOver"
EndPoint="0.5,1"
StartPoint="0.5,0">
<GradientStop Color="#FF000000"
Offset="0.432"/>
<GradientStop Color="#FF808080"
Offset="0.9"/>
<GradientStop Color="#FF848484"
Offset="0.044"/>
<GradientStop Color="#FF787878"
Offset="0.308"/>
<GradientStop Color="#FF212121"
Offset="0.676"/>
</LinearGradientBrush>
如果您需要更多帮助,请与我们联系。