隐式转换

隐式过渡会自动以动画方式呈现特定 UIElement 属性的更改。 无需编写显式动画代码,而是将转换对象附加到属性,WinUI 3 可平滑地对任何值更改进行动画处理。

WinUI 3 提供三个转换类:

过渡类 动画
ScalarTransition OpacityRotation
Vector3Transition ScaleTranslation
BrushTransition Background;;公开 ForegroundTransition 的元素上的 Foreground(例如 TextBlock

对不透明度更改进行动画处理

ScalarTransition 附加到 OpacityTransition 属性,以实现不透明度变化的动画效果:

<Rectangle x:Name="MyRect" Width="80" Height="80" Opacity="1.0">
    <Rectangle.OpacityTransition>
        <ScalarTransition />
    </Rectangle.OpacityTransition>
</Rectangle>

当你在代码中更改 MyRect.Opacity 时,WinUI 3 会自动为这一变化添加动画效果:

MyRect.Opacity = 0.2;  // Animates from 1.0 to 0.2

对旋转更改进行动画处理

将一个 ScalarTransition 附加到 RotationTransition 属性:

<Rectangle x:Name="MyRect" Width="80" Height="80">
    <Rectangle.RotationTransition>
        <ScalarTransition />
    </Rectangle.RotationTransition>
</Rectangle>
// Read ActualWidth/ActualHeight in Loaded or SizeChanged — they are 0 until layout runs.
private void MyRect_Loaded(object sender, RoutedEventArgs e)
{
    MyRect.CenterPoint = new System.Numerics.Vector3(
        (float)MyRect.ActualWidth / 2,
        (float)MyRect.ActualHeight / 2,
        0f);
    MyRect.Rotation = 90;  // Animates to 90 degrees
}

对缩放更改进行动画处理

将一个 Vector3Transition 添加到 ScaleTransition 属性:

<Rectangle x:Name="MyRect" Width="80" Height="80">
    <Rectangle.ScaleTransition>
        <Vector3Transition />
    </Rectangle.ScaleTransition>
</Rectangle>
MyRect.Scale = new System.Numerics.Vector3(1.5f, 1.5f, 1.0f);  // Animates scale up

对翻译更改进行动画处理

Vector3Transition 附加到 TranslationTransition 属性上:

<Rectangle x:Name="MyRect" Width="80" Height="80">
    <Rectangle.TranslationTransition>
        <Vector3Transition />
    </Rectangle.TranslationTransition>
</Rectangle>
MyRect.Translation = new System.Numerics.Vector3(100, 0, 0);  // Moves 100px right

动画化背景画笔更改

BrushTransition 附加到面板的 BackgroundTransition 属性或 ContentPresenter

<ContentPresenter x:Name="MyPresenter" Width="80" Height="80" Background="Blue">
    <ContentPresenter.BackgroundTransition>
        <BrushTransition />
    </ContentPresenter.BackgroundTransition>
</ContentPresenter>
// Animate from Blue to Yellow when the background is replaced with a new brush
MyPresenter.Background = new SolidColorBrush(Colors.Yellow);

注释

BrushTransition两个单独的画笔实例之间制作动画效果。 在现有 SolidColorBrush 对象上设置新颜色不会触发切换。 分配用于触发动画的新 SolidColorBrush 对象。

配置转换持续时间

默认情况下,过渡动画使用由平台定义的时长。 可以使用 Duration 属性覆盖它:

<Rectangle.OpacityTransition>
    <ScalarTransition Duration="0:0:0.5" />
</Rectangle.OpacityTransition>

Duration 值是 hours:minutes:seconds 格式为 TimeSpan 的值,带有可选的秒小数部分(例如,0:0:0.5 表示 500 毫秒)。

WinUI 3 Gallery 应用包含大多数 WinUI 3 控件和功能的交互式示例。