[英]C# WPF how to set location,width and height of the controls programmatically?
[英]Cannot set width or height of animated control in WPF programmatically (not even through Snoop)
这可能与动画有关。 我有一个WPF控件,我正在通过几个不同的情节提要板设置动画的宽度和高度。 我创建情节提要,然后在它们上调用Begin()。 我提供了以下故事板外观的代码。
我想重新评估某个事件的控件大小(例如,窗口大小调整),以使其与动画值不同。 我试图通过设置控件的Width
和Height
属性来手动处理SizeChanged(在动画运行之后)。 调试器显示未设置这些值(保留原始值)。
当我通过探听检查WPF时,“宽度”和“高度”行以桃红色/橙色突出显示,并且尝试再次通过其设置值并不能持久化(我将焦点移开时会显示原始值。我的猜测是动画在某种程度上超越了对属性的手动更改,但是我不确定这是否正确或如何解决。
故事板类
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
该值未更改。 但是,仅将其更改为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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.