XAML WinUI 3桌面MVVM;是否在属性更改时使TextBlock具有动画效果?

xam8gpfp  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(198)

Hi I'm trying to figure out how to animate a TextBlock when it's property updates. New to WinUI3/XAML but I've found https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/how-to-apply-animations-to-text which gives a lot of examples that work, but they all use TextBlock.Loaded. I've tried changing it to TargetUpdated, SourceUpdated, FrameWork.x, Binding.x etc, all crash so I'm not sure what to put in there. Lot's of example on the net, but ones I can find seem to be either WPF or UWP which still crash.
My code which is pretty much same as MS's examples sans binding:

<TextBlock Text="{x:Bind Path=Viewmodel.UpdatedText, Mode=OneWay}">
  <TextBlock.Foreground>
    <SolidColorBrush x:Name="MySolidColorBrush" Color="Maroon" />
  </TextBlock.Foreground>

  <TextBlock.Triggers>
    <EventTrigger RoutedEvent="TextBlock.Loaded">
      <BeginStoryboard>
        <Storyboard>
          <ColorAnimation AutoReverse="True" Storyboard.TargetName="MySolidColorBrush" Storyboard.TargetProperty="Color" From="DarkOrange" To="SteelBlue" Duration="0:0:1" />
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </TextBlock.Triggers>
</TextBlock>

Which does work, when it loads, but I would like to animate it when the text is updated.
One of the examples I found was Animate textblock when the value changes , but it uses .Loaded as well. In the comments it mentions "You have to set the NotifyOnTargetUpdated property to true in the Binding", but NotifyOnTargetUpdated doesn't seem to exist (in WinUI?).
Answer is probably simple but I'm a bit lost on this. I'm also using MVVM pattern so avoiding code behind, but it seems like something this simple shouldn't need it looking at Microsoft's examples? Though If I'm please feel free to correct me. Thanks!

cunj1qz1

cunj1qz11#

在这种情况下,试图“避免代码隐藏”通常是错误的。视图相关的逻辑应该使用编程语言在视图(或控件)中实现。这 * 不会 * 以任何方式破坏MVVM模式,因为该模式并不是试图从视图中首先消除代码。
使用XAML之类的 * 标记 * 语言来实现非常高级的UI逻辑通常是一种反模式,在UWP和WinUI 3的情况下,甚至不可能使用触发器来完成所需的操作。
引用ReactiveUI docs的话,“C#是一种比XAML更有表达力、更简洁的语言,虽然您可以在不编写任何代码的情况下创建整个复杂的视图,但结果将是不可维护的、难以阅读的混乱。”
我的建议是以编程方式实现动画,或者直接在视图的代码隐藏中实现,或者作为附加行为或自定义控件的一部分实现。

相关问题