![](/img/trans.png)
[英]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.