点击或聚焦TextBox时如何为Grid的宽高变更添加过渡动画
你可以在现有DataTrigger的基础上新增EnterActions和ExitActions节点,在节点内添加过渡动画替换瞬时赋值的Setter,即可实现状态切换的动画效果,修改后的完整代码如下:
<Grid HorizontalAlignment="Center" Margin="0,-180,0,0"> <Grid.Style> <Style TargetType="{x:Type Grid}"> <Setter Property="Background" Value="White"/> <Setter Property="Width" Value="350"/> <Setter Property="Height" Value="150"/> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=myTextBox, Path=IsFocused}" Value="True"> <!-- 文本框获得焦点时触发的进入动画 --> <DataTrigger.EnterActions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="Width" To="320" Duration="0:0:0.3" /> <DoubleAnimation Storyboard.TargetProperty="Height" To="120" Duration="0:0:0.3" /> <ColorAnimation Storyboard.TargetProperty="Background.Color" To="#FFF7F7F7" Duration="0:0:0.3" /> </Storyboard> </BeginStoryboard> </DataTrigger.EnterActions> <!-- 文本框失去焦点时触发的回退动画 --> <DataTrigger.ExitActions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="Width" To="350" Duration="0:0:0.3" /> <DoubleAnimation Storyboard.TargetProperty="Height" To="150" Duration="0:0:0.3" /> <ColorAnimation Storyboard.TargetProperty="Background.Color" To="White" Duration="0:0:0.3" /> </Storyboard> </BeginStoryboard> </DataTrigger.ExitActions> </DataTrigger> </Style.Triggers> </Style> </Grid.Style> </Grid>
可以根据需要调整动画参数:
- 调整
Duration属性的取值即可修改过渡时长,格式为小时:分钟:秒,示例中300毫秒的过渡效果比较自然 - 如需添加缓动效果可以给动画节点增加
EasingFunction属性,比如QuadraticEase、CubicEase等预设缓动函数可以让运动效果更顺滑
内容的提问来源于stack exchange,提问作者fs_tigre
相关产品推荐
相关产品推荐

