gpt4 book ai didi

c# - 无法以编程方式在 WPF 中设置动画控件的宽度或高度(甚至不能通过 Snoop)

转载 作者:行者123 更新时间:2023-11-30 12:29:14 25 4
gpt4 key购买 nike

这可能与动画有关。我有一个 WPF 控件,我通过几个不同的 Storyboard 对其宽度和高度进行动画处理。我创建 Storyboard,然后在它们上调用 Begin()。我已经提供了 Storyboard如下所示的代码。

我想在某些事件(例如窗口调整大小)上重新评估控件大小,以便它不同于动画的值。我尝试通过设置控件的 WidthHeight 属性在 SizeChanged 上手动处理此问题(在动画运行后)。调试器显示未设置这些值(保留原始值)。

当我通过 Snoop 检查 WPF 时,Width 和 Height 行以桃色/橙色突出显示,并且尝试通过它再次设置值时不会保留它(当我将焦点移开时会显示原始值。我的猜测是我的动画以某种方式覆盖了对属性的手动更改,但我不确定这是否属实或如何解决。

Storyboard类

public class MyAnimationClass
{
private Storyboard _myStoryboard;
private DoubleAnimation _animation1;
private DoubleAnimation _animation2;
private DoubleAnimation _animation3;

private void InitializeStoryboard()
{
_myStoryboard = CreateMyStoryboard(out _animation1, out _animation2, out _animation3);
}

private Storyboard CreateMyStoryboard(out DoubleAnimation animation1, out DoubleAnimation animation2, out DoubleAnimation animation3)
{
var myStoryboard = new Storyboard();

// create animations
animation1 = new DoubleAnimation { Duration = new TimeSpan(0, 0, 0, 0, 250), From = 0, To = 0 };
animation2 = new DoubleAnimation { BeginTime = new TimeSpan(), Duration = new TimeSpan(0, 0, 0, 0, 250), From = 35, To = 35 };
animation3 = new DoubleAnimation { BeginTime = new TimeSpan(0, 0, 0, 0, 250), Duration = new TimeSpan(0, 0, 0, 0, 250), From = 35, To = 0 };

Storyboard.SetTargetProperty(animation1, new PropertyPath(FrameworkElement.WidthProperty));
Storyboard.SetTargetProperty(animation2, new PropertyPath(FrameworkElement.HeightProperty));
Storyboard.SetTargetProperty(animation3, new PropertyPath(FrameworkElement.HeightProperty));

myStoryboard.Children.Add(animation1);
myStoryboard.Children.Add(animation2);
myStoryboard.Children.Add(animation3);

return myStoryboard;
}

public void Animate(Control controlToAnimate)
{
// ....

var finalWidth = CalculateFinalWidth();
var finalHeight = CalculateFinalHeight();

_animation1.To = finalWidth;
_animation3.To = finalHeight;
_myStoryboard.Begin(controlToAnimate);
}
}

当我想要设置动画时,我会在我的 MyAnimationClass 类的实例上调用 Animate()

想法?

最佳答案

这最终是一个非常简单的修复。由于 FillBehavior 控制属性值,该值没有改变。然而,简单地将它更改为 FillBehavior.Stop 并没有解决我的问题,因为当我的非动画代码设置宽度/高度时,下次我的动画运行时它会动画到我想要的宽度/高度然后默认回到设置的高度。这是通过在计算之后和动画之前设置控件的宽度/高度来解决的:

public void Animate(Control controlToAnimate)
{
// ....

var finalWidth = CalculateFinalWidth();
var finalHeight = CalculateFinalHeight();

// set values here so after animation they stay
controlToAnimate.Width = finalWidth;
controlToAnimate.Height = finalHeight;

_animation1.To = finalWidth;
_animation3.To = finalHeight;
_myStoryboard.Begin(controlToAnimate);
}

关于c# - 无法以编程方式在 WPF 中设置动画控件的宽度或高度(甚至不能通过 Snoop),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19010446/

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