在DragEnter上更改背景

时间:2011-09-23 15:58:29

标签: wpf

我希望在触发DragEnter事件时更改框架元素的背景,并在触发DragLeave事件时恢复其背景。另外,我想要以一种风格应用它。

这是我目前所拥有的:

<EventTrigger RoutedEvent="Button.DragEnter">
            <BeginStoryboard x:Name="DragHoverStoryboard">
                <Storyboard>
                    <DoubleAnimation Storyboard.Target="??????????"
                                     Storyboard.TargetProperty="Background"
                                     Duration="0:0:0"
                                     To="{DynamicResource HoverBrush}" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
        <EventTrigger RoutedEvent="Button.DragLeave">
            <StopStoryboard BeginStoryboardName="DragHoverStoryboard" />
        </EventTrigger>
        <EventTrigger RoutedEvent="Button.Drop">
            <StopStoryboard BeginStoryboardName="DragHoverStoryboard" />
        </EventTrigger>

这里的问题是我无法通过名称应用目标,因为此样式可以应用于任何FrameworkElement。如何将目标应用于样式附加到的元素?

1 个答案:

答案 0 :(得分:1)

Storyboard.Target不是问题,只是把它留下来。但是,您需要更改动画的其余部分。要为颜色设置动画,请使用ColorAnimation而不是DoubleAnimation。此外,属性“背景”不包含颜色而是包含画笔,因此请将属性“Background.Color”设置为动画。这是一个有效的例子:

<Style TargetType="Button">
    <Setter Property="Background" Value="Red"/>
    <Style.Triggers>
        <EventTrigger RoutedEvent="Button.DragEnter">
            <BeginStoryboard x:Name="DragHoverStoryboard">
                <Storyboard>
                    <ColorAnimation Storyboard.TargetProperty="Background.Color" 
                                    Duration="0:0:0" To="Green" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
        <EventTrigger RoutedEvent="Button.DragLeave">
            <BeginStoryboard>
                <Storyboard>
                    <ColorAnimation Storyboard.TargetProperty="Background.Color" 
                                    Duration="0:0:0" To="Red" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Style.Triggers>
</Style>