用户控件:为按钮的背景添加动画效果

12
我希望在鼠标移到按钮上时,能够使按钮的背景动起来。
该按钮的背景绑定了我在用户控件中代码后台创建的自定义依赖属性。
... Background="{Binding BGColor, Elementname="QButton"}"

现在,如果我尝试使用动画来改变按钮的背景

<Trigger Property="IsMouseOver" Value="True">
    <Trigger.EnterActions>
        <BeginStoryboard>
            <Storyboard>
                <ColorAnimation To="LightBlue"
                                Duration="0:0:2"
                                Storyboard.TargetProperty="Background.Color"/>
            </Storyboard>
        </BeginStoryboard>
    </Trigger.EnterActions>
</Trigger>

我收到了一个异常,错误消息为:

无法对不可变属性进行动画处理(或类似错误)。

我该如何解决这个问题?


这些文章可能会有所帮助:http://blogs.msdn.com/b/mikehillberg/archive/2006/09/26/cannotanimateimmutableobjectinstance.aspx 和 https://dev59.com/8m3Xa4cB1Zd3GeqPdVXG。 - spaceplane
2个回答

3

基于 Mike Hillberg 的文章Cannot animate '...' on an immutable object instance的内容:

作为一种解决方法,您可以更新绑定以使 Button 的画笔进行复制。这不会干扰绑定 - 对窗口前景的任何更改仍将传播到 Button,但是 Button 将为本地动画制作自己的副本。

因此,您的完整解决方案应该像这样:

<Window x:Class="WpfApplication2.Window3"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:local="clr-namespace:WpfApplication1"
    ....
    ....

Background="{Binding BGColor, Converter={x:Static local:MyCloneConverter.Instance}}"

这是引用了一个IValueConverter,用于绑定,看起来像这样:

class MyCloneConverter : IValueConverter
{
    public static MyCloneConverter Instance = new MyCloneConverter();

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is Freezable)
        {
            value = (value as Freezable).Clone();
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

0

改变 DP(BGColor)本身以更改背景。

<Button.Triggers>
    <EventTrigger RoutedEvent="MouseEnter">
        <BeginStoryboard>
            <Storyboard>
                <ColorAnimation To="Red" 
                        Duration="0:0:2" 
                        Storyboard.TargetName="QButton"
                        Storyboard.TargetProperty="(BGColor).(SolidColorBrush.Color)"/>
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
</Button.Triggers>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接