Home > OS >  WinUI 3 Desktop MVVM; Animate TextBlock on property change?
WinUI 3 Desktop MVVM; Animate TextBlock on property change?

Time:04-12

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://docs.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!

CodePudding user response:

Trying to "avoid code-behind" in cases like this is usually a mistake. View-related logic should be implemented in the view (or control) using a programming language. This does not break the MVVM pattern in any way as the pattern is not about trying to eliminate code from the views in the first place.

Using a markup language such as XAML to implement farily advanced UI logic is generally an antipattern and in the case of UWP and WinUI 3, it's not even possible to use triggers to accomplish what you want.

To quote the ReactiveUI docs, "C# is a much more expressive, more concise language than XAML, and while it may be possible for you to create an entire complex view without writing any code, the result will be an unmaintainable, difficult to read mess."

My suggestion would be to implement the animation programmtically, either directly in the code-behind of the view or as part of an attached behaviour or custom control.

  • Related