Avalonia 使用动画改编文本控件背景色

今天使用动画修改文本控件背景色遇到了两个问题,不知道是坑还是自己使用姿势不对,遇到两个问题:

在xaml中写Animation写Setter改编背景色编译报错

    <Window.Resources>
        <LinearGradientBrush x:Key="raiseBrush" StartPoint="0.5,0.5" EndPoint="1,0.5">
            <LinearGradientBrush.GradientStops>
                <GradientStop Offset="0" Color="#00000000"></GradientStop>
                <GradientStop Offset="1" Color="#FFEE0000"></GradientStop>
            </LinearGradientBrush.GradientStops>
        </LinearGradientBrush>
        <LinearGradientBrush x:Key="fallBrush" StartPoint="0.5,0.5" EndPoint="1,0.5">
            <LinearGradientBrush.GradientStops>
                <GradientStop Offset="0" Color="#00000000"></GradientStop>
                <GradientStop Offset="1" Color="#FF00CC00"></GradientStop>
            </LinearGradientBrush.GradientStops>
        </LinearGradientBrush>
        <Animation x:Key="riseAnimation" Duration="0:0:1"  >
            <KeyFrame Cue="0.0" >
                <Setter  Property="TextBlock.Background" Value="{StaticResource raiseBrush}"></Setter>
            </KeyFrame>
            <KeyFrame Cue="1.0">
                <Setter Property="TextBlock.Background" Value="{StaticResource raiseBrush}"></Setter>
            </KeyFrame>
        </Animation>
    </Window.Resources>

提示

Error AVLN2200 Avalonia: Could not determine target type of Setter Line 23, position 18.

不能写Setter么?

我的解决方案:在.cs文件中,使用c#代码创建动画.

KeyFrame frame0 = new KeyFrame();
frame0.Cue = new Cue(0d);
frame0.Setters.Add(new Setter(BackgroundProperty, raiseBrush));
KeyFrame frame1 = new KeyFrame();
frame1.Cue = new Cue(1d);
frame1.Setters.Add(new Setter(BackgroundProperty, raiseBrush));
var raisedAnimation = new Animation()
{
    Duration = TimeSpan.FromSeconds(1d),
};
raisedAnimation.Children.Add(frame0);
raisedAnimation.Children.Add(frame1);

raisedAnimation.RunAsync(priceTextBlock);

文本控件的背景色和动画中设置的背景色类型需要一致

<StackPanel>
    <Button Content="点击变颜色" Name="clickBtn" Click="ClickBtn_OnClick"></Button>
    <TextBlock Name="priceTextBlock" Text="价格" Background="White" />
</StackPanel>

如上我给priceTextBlock设置了White;在动画中给它设置了渐变色,结果运行起来报错了.
image
Unable to cast object of type 'Avalonia.Media.Immutable.ImmutableSolidColorBrush' to type 'Avalonia.Media.IGradientBrush'.
我去看了一下avalonia的源代码:
image
然后使用dotpeek看了一下类型架构图,这俩接口确实没有父子关系;
image
解决方案想必你也心中有数了.

小结:动画这个小技巧竟遇到了两个"坑";此外实测在WPF中使用类似的代码并不会出现这些问题.

posted @ 2026-06-08 23:11  BigBosscyb  阅读(12)  评论(0)    收藏  举报