从孩子那里访问父母的姓名范围

时间:2014-05-15 16:57:43

标签: c# wpf xaml

在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的名称范围呢? ColorAniamtion应该使用foreground属性访问setter并更改颜色。

1 个答案:

答案 0 :(得分:0)

为按钮的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>