WPF中Grid展开动画从侧边触发,如何修改为从中心向外展开
WPF Grid实现中心向外展开动画方案
问题原因
你当前通过动画直接修改FrameworkElement.Height的实现,受WPF默认布局锚定规则影响,控件会从布局容器的顶边/侧边开始拉伸,因此呈现从侧边展开的效果,无法实现中心扩散的表现。
推荐实现(渲染缩放方案,流畅无布局抖动)
核心思路是放弃直接修改控件宽高,改用ScaleTransform做缩放动画,同时将控件的渲染变换原点设置为中心位置,动画过程不触发布局重新计算,流畅度更高。
第一步:修改Grid控件定义
给目标Grid添加渲染变换配置,将变换锚点设为控件中心:
<!-- 保留Grid原有布局属性(比如高度222、背景、内部内容等都不需要改) --> <Grid x:Name="ExpandingGrid" RenderTransformOrigin="0.5,0.5"> <Grid.RenderTransform> <ScaleTransform x:Name="GridScaleTransform" ScaleX="0" ScaleY="0"/> </Grid.RenderTransform> <!-- 此处放Grid原有的所有子内容 --> </Grid>
第二步:替换原有Storyboard动画
将原来修改Height的动画,替换为同时对ScaleX、ScaleY两个缩放属性做动画,保留你原有的时间逻辑(前1秒静止,后2秒完成展开):
<Window.Resources> <Storyboard x:Key="ExpandingAnimation"> <!-- 水平方向缩放动画 --> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="GridScaleTransform" Storyboard.TargetProperty="ScaleX"> <EasingDoubleKeyFrame KeyTime="00:00:00" Value="0"/> <EasingDoubleKeyFrame KeyTime="00:00:01" Value="0"/> <EasingDoubleKeyFrame KeyTime="00:00:03" Value="1"> <!-- 可选:添加缓动函数让展开效果更自然,不需要可删除此段 --> <EasingDoubleKeyFrame.EasingFunction> <CubicEase EasingMode="EaseOut"/> </EasingDoubleKeyFrame.EasingFunction> </EasingDoubleKeyFrame> </DoubleAnimationUsingKeyFrames> <!-- 垂直方向缩放动画 --> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="GridScaleTransform" Storyboard.TargetProperty="ScaleY"> <EasingDoubleKeyFrame KeyTime="00:00:00" Value="0"/> <EasingDoubleKeyFrame KeyTime="00:00:01" Value="0"/> <EasingDoubleKeyFrame KeyTime="00:00:03" Value="1"> <EasingDoubleKeyFrame.EasingFunction> <CubicEase EasingMode="EaseOut"/> </EasingDoubleKeyFrame.EasingFunction> </EasingDoubleKeyFrame> </DoubleAnimationUsingKeyFrames> </Storyboard> </Window.Resources>
第三步:后台代码无需修改
你原来在构造函数里启动动画的C#逻辑可以完全保留,不需要做任何调整:
public MainWindow() { InitializeComponent(); Storyboard ExpandingAnime = (Storyboard)TryFindResource("ExpandingAnimation"); ExpandingAnime.Begin(); }
备选方案(直接修改宽高,不推荐)
如果一定要通过修改宽高实现,需要把Grid的水平、垂直对齐方式都设为Center,同时在动画里同时修改Width和Height从0到目标值。但这种方案动画过程中会持续触发布局重算,流畅度差,容易出现抖动,仅作为参考:
<Grid x:Name="ExpandingGrid" VerticalAlignment="Center" HorizontalAlignment="Center" Height="0" Width="0"> <!-- 内容 --> </Grid>
动画里需要同时添加对Width、Height属性的动画,从0过渡到你的目标宽高值即可。
内容的提问来源于stack exchange,提问作者ThatZ Fire
相关产品推荐
相关产品推荐

