我有一个自定义控件,想要添加鼠标悬停时的行为,将整个对象置于z轴顶部,当鼠标移到画布上的其他对象时,将其放回原位。
我有以下XAML代码,其中颜色动画,内部矩形的ZIndex也进行了动画处理(遮盖了椭圆形),但是无法让整个控件置于父级画布中所有其他控件的最前面。以下是问题所在的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,但不能在控件之间进行。我阅读了这篇文章,它暗示我应该能够做到这一点 - 请注意,在我的情况下,模板父级是自定义控件的实例,而不是列表中的元素,因此那种情况下的解决方案似乎不适用。我得到的错误如下:
System.Windows.Data Error: 2 : 找不到目标元素的控制 FrameworkElement 或 FrameworkContentElement。BindingExpression:(no path); DataItem=null; 目标元素为 'Int32AnimationUsingKeyFrames' (HashCode=58939632); 目标属性为“Target”(类型为“DependencyObject”)
在其他地方我已经阅读到,这种方法不起作用,因为从绑定返回的不是依赖对象。现在我已经在代码中使其正常工作,但正在寻找更优雅的XAML解决方案。