从子节点访问父节点'
本文关键字:父节点 子节点 访问 | 更新日期: 2023-09-27 18:03:47
在XAML中,我的代码如下:
<Style TargetType="Button">
<Setter Property="Foreground" Value="#c10000" x:Name="TextColor"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="RootElement" CornerRadius="8">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation Storyboard.TargetName="TextColor"
Storyboard.TargetProperty="Foreground" To="#FF8D00" />
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
这段代码失败,提示"TextColor"在边框的命名范围中找不到。我如何访问名称范围,其中TextColor定义然后?coloranimation应该访问具有前景属性的setter并更改颜色。
为按钮的Foreground
属性设置动画,而不是为Setter
设置动画。由于Foreground
属性的类型是Brush
而不是Color
,所以我在下面的示例代码中使用对象动画而不是颜色动画:
<Button.Style>
<Style TargetType="Button">
<Setter Property="Foreground" Value="#c10000"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="RootElement" CornerRadius="8">
<ContentPresenter/>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="MouseOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Button.Foreground)">
<ObjectAnimationUsingKeyFrames.KeyFrames>
<DiscreteObjectKeyFrame KeyTime="0:0:0">
<DiscreteObjectKeyFrame.Value>
<SolidColorBrush Color="#FF8D00"/>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames.KeyFrames>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>