这就是 ObjectAnimationUsingKeyFrames 的工作原理。由于 Width 是一个 GridLength 类型,所以我们不能使用一些像 DoubleAnimation 这样的内置动画。
所以你可以做的是内容的宽度,而不是像这样:
<Page
x:Class="stofSmoothAnimation.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:stofSmoothAnimation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<Storyboard x:Name="Storyboard1">
<DoubleAnimationUsingKeyFrames EnableDependentAnimation="True" Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="redBorder">
<EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="0"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</Page.Resources>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="col1" Width="Auto"/>
<ColumnDefinition Width="300"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border x:Name="redBorder" Background="Red" Width="300"/>
<Border Background="White" Grid.Column="1"/>
<Border Background="Black" Grid.Column="2">
<Button x:Name="reduceGridWidth" Click="reduceGridWidth_Click"
HorizontalAlignment="Center">
Button
</Button>
</Border>
</Grid>
</Page>
或者您可以通过像这样处理 CompositionTarget.Rendering 事件来自己制作动画:
private void reduceGridWidth_Click(object sender, RoutedEventArgs e)
{
// start handling event
CompositionTarget.Rendering += CompositionTarget_Rendering;
}
void CompositionTarget_Rendering(object sender, object e)
{
col1.Width = new GridLength(col1.Width.Value - 20);
// when the Width hits zero, we stop handling event
if (col1.Width.Value == 0)
{
CompositionTarget.Rendering -= CompositionTarget_Rendering;
}
}
希望这可以帮助!