我有一个自定义控件,我想在其上添加鼠标悬停行为,以将整个对象带到 z 顺序的顶部,然后在鼠标悬停在 Canvas 上的不同对象上时将其放回原位.
我有以下 XAML,其中颜色动画,控件内矩形的 ZIndex 动画(遮挡椭圆),但我无法让整个控件将自己置于父 Canvas 中所有其他控件的前面. XAML 的麻烦部分在下面用空行显示。
<Style TargetType="local:CustomControl1">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:CustomControl1">
<Grid x:Name="PartLayoutRoot">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="MouseOver">
<Storyboard>
<Int32AnimationUsingKeyFrames
Storyboard.Target="{Binding RelativeSource={RelativeSource TemplatedParent} }"
Storyboard.TargetProperty="(Canvas.ZIndex)">
<DiscreteInt32KeyFrame KeyTime="0" Value="99" />
</Int32AnimationUsingKeyFrames>
<Int32AnimationUsingKeyFrames
Storyboard.TargetName="Rect"
Storyboard.TargetProperty="(Canvas.ZIndex)">
<DiscreteInt32KeyFrame KeyTime="0" Value="99" />
</Int32AnimationUsingKeyFrames>
<ColorAnimation To="Red"
Storyboard.TargetName="Rect"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)"
Duration="0:0:1" />
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Rectangle x:Name="Rect" Fill="Blue" Height="40" Width="40" />
<Ellipse Fill="Green" Height="30" Width="30" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
基本上我可以为 ZIndex 内部控件设置动画,但不能为内部控件设置动画。我已阅读 this post这意味着我应该能够做到这一点 - 请注意,在我的情况下,模板父级是自定义控件的实例,而不是列表中的元素,因此该场景中的解决方案似乎不适用。我得到的错误如下
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:(no path); DataItem=null; target element is 'Int32AnimationUsingKeyFrames' (HashCode=58939632); target property is 'Target' (type 'DependencyObject')
在其他地方,我读到这不起作用,因为从 Binding 返回的不是依赖对象。我现在所有这些都在代码中工作,但正在寻找更优雅的 XAML 解决方案。
最佳答案
这里的解决方案是更改 ZIndex
不在 VisualState
模板,但在样式的触发器中。
<Style TargetType="local:CustomControl1">
<Setter Property="Template">
...
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="(Canvas.ZIndex)" Value="99"/>
</Trigger>
</Style.Triggers>
</Style>
希望这可以帮助!
关于wpf - 你可以在 VisualStateManager 中为 TemplatedParent 设置 ZIndex 动画吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23002328/