gpt4 book ai didi

c# - UserControl 动画按钮的背景

转载 作者:可可西里 更新时间:2023-11-01 08:28:49 27 4
gpt4 key购买 nike

如果鼠标位于 Button 上,我想为 ButtonBackground 设置动画。

ButtonBackground 绑定(bind)到我在 UserControl 的代码隐藏中创建的自定义依赖属性

... 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>

我得到一个异常:

cannot animate an immutable property (or similar).

我该如何解决这个问题?

最佳答案

基于 Mike Hillberg 关于 Cannot animate '...' on an immutable object instance 的精彩文章:

As a workaround, you can update the binding to make a copy of the brush for the Button. That doesn't interfere with the binding – any change to the window’s foreground will still be propagated to the Button– but the Button will make its own copy for a local animation.

所以你的完整解决方案应该是这样的:

<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}}"

它正在为看起来像这样的绑定(bind)引用一个 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();
}
}

关于c# - UserControl 动画按钮的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34943422/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com