【发布时间】:2023-03-07 13:15:01
【问题描述】:
我正在尝试创建一个简单的按钮样式,它会在鼠标悬停时将背景的不透明度从 0.0 更改为 1.0(反之亦然)。我正在为所述按钮创建一个模板,并且我正在绑定模板中的所有属性。除了背景中的SolidColorBrush 之外,一切正常,我无法绑定到模板绑定。我已经看到有人提到 TemplateBinding 由于上下文原因不是正确的,但我无法找到另一种解决方案。我怀疑Background 可能是Brush 的问题,我只需要那个画笔的Color 组件,但我无法获得它。
明显的覆盖是创建两个具有两种不同颜色的模板样式(可行),但我想避免这种硬编码和复制粘贴。我想要的是在 Button 上指定 Background 属性的选项,该属性将在 SolidColorBrush 中使用,然后不透明度将完成其余的工作。
<Style TargetType="{x:Type Button}" x:Key="WindowButtonStyle">
<Setter Property="Width" Value="46" />
<Setter Property="Height" Value="32" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
<Border.Background>
<SolidColorBrush x:Name="ButtonBackgroundBrush" Color="???" Opacity="0.0" />
</Border.Background>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}" />
</Border>
<ControlTemplate.Resources>
<Storyboard x:Key="MouseOverAnimation">
<DoubleAnimation Storyboard.TargetName="ButtonBackgroundBrush" Storyboard.TargetProperty="Opacity" To="1.0" Duration="0:0:0.15" />
</Storyboard>
<Storyboard x:Key="MouseOutAnimation">
<DoubleAnimation Storyboard.TargetName="ButtonBackgroundBrush" Storyboard.TargetProperty="Opacity" To="0.0" Duration="0:0:0.15" />
</Storyboard>
</ControlTemplate.Resources>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Trigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource MouseOverAnimation}" />
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard Storyboard="{StaticResource MouseOutAnimation}" />
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
然后,按钮是这样使用的:
<Button x:Name="MinimizeButton" Style="{StaticResource WindowButtonStyle}" Click="MinimizeButton_Click" Background="Green">
<Image Source="../Resources/WindowButtons/Images/win-minimize.png" Width="12" Height="12"></Image>
</Button>
添加了Background="Green" 属性设置来测试它,但没有奏效。
【问题讨论】:
标签: c# wpf windows binding templatebinding