当鼠标悬停在作为按钮模板的路径上时更改填充颜色

3

我有一个按钮,它的Template被设置为显示在VisualBrush中包裹的Path。这个Path已经设定了Fill,但是当鼠标移到按钮上时,我需要改变Fill颜色。

视觉画刷

<VisualBrush x:Key="EditIconBrush" Stretch="Uniform">
    <VisualBrush.Visual>
        <Canvas Width="24" Height="24">
            <Path Fill="White" Data="M20.71,4.04C21.1,3.65 21.1,3 20.71,2.63L18.37,0.29C18,-0.1 17.35,-0.1 16.96,0.29L15,2.25L18.75,6M17.75,7L14,3.25L4,13.25V17H7.75L17.75,7Z" />
        </Canvas>
    </VisualBrush.Visual>
</VisualBrush>

按钮模板

<ControlTemplate x:Key="ButtonIconTemplate" 
                 TargetType="Button">
    <Grid>
        <Rectangle Fill="Transparent" />
        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                            Content="{TemplateBinding Content}"
                            VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
    </Grid>
</ControlTemplate>

<Button DockPanel.Dock="Right" Margin="0 0 10 0" 
        Command="{Binding RelativeSource={RelativeSource AncestorType=Expander}, Path=DataContext.AddFieldCommand}"
        Template="{StaticResource ButtonIconTemplate}">                                        
    <Rectangle Width="20" Height="20" Fill="{DynamicResource EditIconBrush}" />
</Button>

我需要在两种颜色中拥有两个不同版本的路径吗?还是可以在样式中实现?当鼠标悬停时,我想增加路径的大小并将其从灰色更改为白色,然后当鼠标离开时减小大小并将颜色从白色更改为灰色。
我尝试将路径的填充属性绑定到按钮的前景属性上,使用相对路径作为推荐的解决方法。基本上,我想要实现与该线程中原始帖子作者相同的概念。区别在于我的路径在资源字典中而不是我的按钮本身中。
绑定到前景的尝试
<Button DockPanel.Dock="Right" Margin="0 0 10 0" 
        Foreground="White"
        Command="{Binding RelativeSource={RelativeSource AncestorType=Expander}, Path=DataContext.AddFieldCommand}"
        Template="{DynamicResource ButtonIconTemplate}">                                        
    <Rectangle Width="20" Height="20" Fill="{DynamicResource EditIconBrush}" />
</Button>

<VisualBrush x:Key="EditIconBrush" Stretch="Uniform">
    <VisualBrush.Visual>
        <Canvas Width="24" Height="24">
            <Path Fill="{Binding Path=Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" 
                  Data="M20.71,4.04C21.1,3.65 21.1,3 20.71,2.63L18.37,0.29C18,-0.1 17.35,-0.1 16.96,0.29L15,2.25L18.75,6M17.75,7L14,3.25L4,13.25V17H7.75L17.75,7Z" />
        </Canvas>
    </VisualBrush.Visual>
</VisualBrush>

我不确定如何解决这个问题,希望能得到帮助。

1个回答

0
使用IsMouseOver触发器:
<ControlTemplate.Triggers>
    <Trigger Property="IsMouseOver" Value="True">
        <Setter TargetName="NameOfPath" Property="Fill" Value="Colour" />
        <Setter Property="RenderTransform">
            <Setter.Value>
                <ScaleTransform ScaleX="2" ScaleY="2" />
            </Setter.Value>
        </Setter>
        <Setter Property="RenderTransformOrigin" Value="0.5, 0.5" />
    </Trigger>
</ControlTemplate.Triggers>

你需要给你的路径命名(例如:<Path x:Name="NameOfPath" />),并替换适当的颜色,同时使用适当的大小来进行RenderTransform缩放。


请问您能否举个路径名的例子吗?我的编译器说它无法识别我的路径名称,尽管我已经使用了 x:Name 属性进行了精确设置。 - ygoe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接