Hello,
Welcome to Microsoft Q&A!
You can't access the Storyboard animations directly from the ViewModel. You need to manually create a Storyboard animation in the ViewModel when you want to trigger it. Just pass the target element as parameter via command and let the ViewModel to create animation for this.
I've made a simple demo to show how it works.
- Create a ViewModel and ICommand class.
- Create a Button in Xaml which used to trigger the animation and bind the command property to the ViewModel's ICommand.
- Convert your Xaml Storyboard animation to code behind and begin the animation when the button is click.
Since I don't know your scenario and just for test purpose, I will use a Rectangle as target. Create Storyboard animation to move it.
MainPage.Xaml:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Rectangle x:Name="MyRectangle" Grid.Row="1" Fill="Red" Width="500" Height="500"/>
<Button Grid.Row="0" Content="Click" Command="{Binding StartAnimation}" CommandParameter="{Binding ElementName=MyRectangle}"/>
</Grid>
MainPage.cs:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
TestViewModel viewModel = new TestViewModel();
this.DataContext = viewModel;
}
}
ViewModel.cs:
public class TestViewModel
{
public ICommand StartAnimation
{
get
{
return new CommadEventHandler<object>((s) => this.ShowAnimation(s));
}
}
private void ShowAnimation(object targetElement)
{
try
{
Rectangle rectangle = targetElement as Rectangle;
rectangle.RenderTransform = new CompositeTransform();
Storyboard storyboard = new Storyboard();
DoubleAnimation translateXAnimation = new DoubleAnimation();
translateXAnimation.From = -500;
translateXAnimation.To = 1;
translateXAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(500));
Storyboard.SetTarget(translateXAnimation, rectangle);
Storyboard.SetTargetProperty(translateXAnimation, "(UIElement.RenderTransform).(CompositeTransform.TranslateX)");
storyboard.Children.Add(translateXAnimation);
storyboard.Begin();
}
catch (Exception ex)
{
}
}
}
public class CommadEventHandler<T> : ICommand
{
public event EventHandler CanExecuteChanged;
public Action<T> action;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
this.action((T)parameter);
}
public CommadEventHandler(Action<T> action)
{
this.action = action;
}
}
Please note this is just a simple demo which shows how it works. You need to adjust some of the code to fix your real scenario.
Thank you.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.