Improve animation smoothness (moving of controls) - wpf

I have implemented the animation of moving of a grid control in the following manner:
<Grid
HorizontalAlignment="Center"
VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.Style>
<Style TargetType="Grid">
<Style.Triggers>
<DataTrigger
Binding="{Binding ElementName=rootLayout, Path=IsVisible}"
Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ThicknessAnimation
Storyboard.TargetProperty="Margin"
From="-500,0,0,0"
To="0,0,0,0"
Duration="0:0:0.5" />
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
<Border
Grid.RowSpan="2"
Background="Black"
CornerRadius="6" >
<Border.Effect>
<DropShadowEffect />
</Border.Effect>
</Border>
<TextBlock
Grid.Row="0"
Width="400"
Height="200"
Margin="20,20,20,10"
Text="{Binding Path=MessageText}" />
<Button
Grid.Row="1"
Margin="20,5,20,15"
HorizontalAlignment="Right"
Width="75"
Content="OK"
Command="{Binding Path=CloseDialogCommand}" />
</Grid>
The animation works fine, but it's ugly. It is shaky / jittery / jerky and it really looks unprofessional. Is there a way to improve this? Am I using the right approach with animating the value change on the Margin property in order to move the grid? I've read about RenderTransform, but I don't know how to use it in my case.
Also, the animation looks unnatural. I know this can be improved but I don't know how. What are these properties and can they help me enhance my animation:
AccelerationRatio
DecelerationRatio
EasingFunction
IsAdditive
IsCumulative
SpeedRatio
Thanks for helping!
P.S. I am trying to put as much code as possible in XAML, so I'd prefer that approach, but really, if there's anything to improve this...

Use easing functions, a simple DoubleAnimation and RenderTransform, e.g.
<Button Content="Test">
<Button.RenderTransform>
<TranslateTransform/>
</Button.RenderTransform>
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="RenderTransform.X"
From="-500" To="0">
<DoubleAnimation.EasingFunction>
<CubicEase EasingMode="EaseOut"/>
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
This should be quite smooth, check out this overview on easing functions to get an idea of how they affect the animation.
Also note that the duration has a strong effect on what an animation looks like, depending on what easing function you use setting high duration values is needed because they slow down significantly at the end.

Related

Expander getting stuck after IsExpanded set to true by storyboard

So I have an expander that I want to have the normal functionality (open and close with its own button) but I also want a different button to expand it when pressed (this button is in the header of the expander). I'm using a storyboard in an event trigger for the Button.Click which works, but after it is expanded this way the normal button doesn't work, it just stays expanded. My xaml is below, I would really prefer to keep this all in the xaml, I could come up with a way to do it in the codebehind/viewmodel myself.
<Expander x:Name="IndexExpander" IsExpanded="True" Grid.Row="4" Grid.ColumnSpan="5" Margin="10" MaxHeight="150">
<Expander.Triggers>
<EventTrigger SourceName="btnAddIndex" RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="IndexExpander" Storyboard.TargetProperty="IsExpanded" BeginTime="0:0:0.25" Duration="0:0:0.20" >
<DiscreteBooleanKeyFrame KeyTime="0" Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Expander.Triggers>
<Expander.Header>
<StackPanel DockPanel.Dock="Left" Orientation="Horizontal">
<TextBlock Text="Indexes" FontWeight="Bold"/>
<!-- Add/Delete Buttons-->
<Grid Margin="10,0,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*"/>
<ColumnDefinition Width="50*"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" x:Name="btnAddIndex" Command="{Binding AddIndexCommand}" Template="{StaticResource AddButtonTemplate}" IsEnabled="{Binding IsEditable}" Margin="0,0,5,0" />
</Grid>
</StackPanel>
</Expander.Header>
Alright, so for anyone following in my footsteps here's what I did. I got the idea from here, and adapted it until it worked correctly.
<Expander.Triggers>
<EventTrigger SourceName="btnAddCol" RoutedEvent="Button.Click">
<BeginStoryboard x:Name="ColumnExpanderStory">
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="ColumnExpander" Storyboard.TargetProperty="IsExpanded">
<DiscreteBooleanKeyFrame KeyTime="0" Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="ToggleButton.PreviewMouseUp">
<RemoveStoryboard BeginStoryboardName="ColumnExpanderStory" />
</EventTrigger>
</Expander.Triggers>
<Expander.Header>
The problem was that the storyboard overrides any other bindings to the IsExpanded property, so it has to be removed to restore them (read more here). The suggestion was to use the ToggleButton.Checked event to remove the storyboard, but that didn't work for me, only the "Preview" events seemed to have the right timing. I started with PreviewMouseDown, but it would remove the storyboard, then on mouse up toggle the expander, meaning the first click would just flip states back and forth quickly. Using PreviewMouseUp got around that issue.

Access ItemsControl Items and Animate One by One

Today is a good day since I started with WPF, this for a launcher I'm creating.
Using the following code, I managed to get the result to be seen in the screenshot:
<Grid>
<ItemsControl ItemsSource="{Binding Programs}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Text}" Background="Transparent" Foreground="White" Width="128" Height="150" >
<Button.RenderTransform>
<TransformGroup>
<ScaleTransform />
</TransformGroup>
</Button.RenderTransform>
<Button.Template>
<ControlTemplate TargetType="Button">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Image Grid.Row="0" Source="{Binding Image}" Height="128" />
<ContentPresenter Grid.Row="1" HorizontalAlignment="Center" Margin="3,10" />
<Rectangle Grid.Row="0" Fill="{TemplateBinding Background}" />
<Rectangle Grid.Row="1" Fill="{TemplateBinding Background}" />
</Grid>
</ControlTemplate>
</Button.Template>
<Button.Resources>
<Storyboard SpeedRatio="4" x:Key="MouseEnterStoryboard" x:Name="MouseEnterStoryboard">
<ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" To="#22FFFFFF"></ColorAnimation>
</Storyboard>
<Storyboard SpeedRatio="4" x:Key="MouseLeaveStoryboard" x:Name="MouseLeaveStoryboard">
<ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" To="Transparent"></ColorAnimation>
</Storyboard>
<Storyboard Duration="00:00:00.05" x:Key="MouseClickStoryboard" AutoReverse="True">
<DoubleAnimation To="0.8" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"/>
<DoubleAnimation To="0.8" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"/>
</Storyboard>
<Storyboard x:Key="WindowLoadedStoryboard">
<DoubleAnimation Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="00:00:01" />
</Storyboard>
</Button.Resources>
<Button.Triggers>
<EventTrigger RoutedEvent="Mouse.MouseEnter">
<BeginStoryboard Storyboard="{StaticResource MouseEnterStoryboard}" />
</EventTrigger>
<EventTrigger RoutedEvent="Mouse.MouseLeave">
<BeginStoryboard Storyboard="{StaticResource MouseLeaveStoryboard}" />
</EventTrigger>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard Storyboard="{StaticResource MouseClickStoryboard}" />
</EventTrigger>
<EventTrigger RoutedEvent="Window.Loaded">
<BeginStoryboard Storyboard="{StaticResource WindowLoadedStoryboard}"></BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
Screenshot:
Now, for each item in the list bound to this control, it will create a button.
How would I access this button programmatically, better yet, how would I access one of the Storyboards programatically since assigning a name (x:to them simply won't do the trick it seems...
Also, how can I animate the buttons one by one? Currently they each fade in at exact the same time (# WindowLoadedStoryboard), but I would like to let each button fade in one by one with a short delay, to create a nice effect. How would I achieve this?
Hope someone can answer these 2 questions for me!
Greetings!
Your problem with accessing the elements defined in the DataTemplate is caused because you defined those elements in a DataTemplate... those elements could be rendered in many different types of UI container controls. You can find the solution in the How to: Find DataTemplate-Generated Elements page from MSDN.
You first need to get hold of the relevant container control that contains the item that has had that DataTemplate applied to it. Next, you need to get the ContentPresenter from that container control and then you can get the DataTemplate from ContentPresenter. Finally, you can access the named elements from the DataTemplate. From the linked page:
// Getting the currently selected ListBoxItem
// Note that the ListBox must have
// IsSynchronizedWithCurrentItem set to True for this to work
ListBoxItem myListBoxItem = (ListBoxItem)(myListBox.ItemContainerGenerator.
ContainerFromItem(myListBox.Items.CurrentItem));
// Getting the ContentPresenter of myListBoxItem
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
// Finding textBlock from the DataTemplate that is set on that ContentPresenter
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
TextBlock myTextBlock =
(TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter);
// Do something to the DataTemplate-generated TextBlock
MessageBox.Show("The text of the TextBlock of the selected list item: " +
myTextBlock.Text);

WPF Visibility animation trigger problems

I have two stackpanels, where the second panel is extra information that can be slided down and shown when clicking on a button (like jQuerys slideDown effect). And afterwards be slided up, when clicking the button again.
I´ve never been fiddling with animations before, but have been doing some research. I´m still quite confused though, and cant figure out this simple problem.
When I only listen on the Visibility=Visible property, it works fine. But when I also want to slide the panel up, it behaves weird.
This is my XAML code:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Width="600" Orientation="Horizontal">
<TextBlock Style="{StaticResource Heading4}">Panel 1</TextBlock>
<Button Width="300" Margin="30,0,0,0" Click="Button_OnClick">Click to slide other panel down</Button>
</StackPanel>
<StackPanel Name="StackPanelShowHide" Grid.Row="1" Width="500" Orientation="Vertical" Background="Beige" Height="70">
<StackPanel.Style>
<Style TargetType="StackPanel">
<Style.Triggers>
<Trigger Property="Visibility" Value="Visible">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Height" From="0" To="70" Duration="0:0:1" />
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
<Trigger Property="Visibility" Value="Collapsed">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Height" From="70" To="0" Duration="0:0:1" />
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
</Style.Triggers>
</Style>
</StackPanel.Style>
<TextBlock Style="{StaticResource Heading4}">New panel</TextBlock>
</StackPanel>
</Grid>
And this is my Codebehind:
private void Button_OnClick(object Sender, RoutedEventArgs E) {
if (StackPanelShowHide.Visibility == Visibility.Collapsed) {
StackPanelShowHide.Visibility = Visibility.Visible;
} else {
StackPanelShowHide.Visibility = Visibility.Collapsed;
}
}
Really hope you can help :)
Kind regards,
Lars
I guess that instead of slide up animation on collapse it just instantly disappears. This is because you set Visibility to Collapsed, so there is nothing to display.
To fix this:
a) use MVVM: add some property to ViewModel and trigger on it. Modify property via ICommand.
b) Do not set Visibility, just start proper Storyboard in event handler.
I believe that your problem is that when the StackPanel has a Visibility value of Collapsed, it is removed from the UI. Therefore, even if the Animation were to occur, you would not see it.

How to use animation to change size of grid?

I would like to enlarge (i.e. ScaleTransform) a whole grid depending on a property of my custom class.
My Grid
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="2*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Viewbox Style="{StaticResource InvViewBoxStyle}" Grid.Column="1" Grid.Row="0">
<TextBlock Style="{StaticResource InvBoxTextStyle}" Text="{Binding BoxId}" />
</Viewbox>
<Viewbox Style="{StaticResource InvViewBoxStyle}" Grid.Column="1" Grid.Row="1" >
<TextBlock Style="{StaticResource InvBoxTextStyle}" Text="{Binding ProdNr}" />
</Viewbox>
</Grid>
This is the style I used. The problem is, there is no scaling to be seen at all. I tested the code with another animation (changing the background color) which worked fine.
<Style x:Key="InvViewBoxStyle" TargetType="Viewbox">
<Setter Property="LayoutTransform">
<Setter.Value>
<ScaleTransform />
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding IsReadyToUnload}" Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="LayoutTransform.ScaleX" To="2" Duration="0:0:0.5" />
<DoubleAnimation Storyboard.TargetProperty="LayoutTransform.ScaleY" To="2" Duration="0:0:0.5" />
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
Could you give me any hints on how to achieve the correct scaling behavior?
Try attaching this to your ViewBox.
<Viewbox x:Name="viewbox" RenderTransformOrigin="0.5,0.5" ...>
<Viewbox.RenderTransform>
<TransformGroup>
<ScaleTransform/>
</TransformGroup>
</Viewbox.RenderTransform>
Also try changing your animation to this, name your first ViewBox viewbox.
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" Storyboard.TargetName="viewbox">
<EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="2"/>
</DoubleAnimationUsingKeyFrames>
Sorry, didn't see that you are using LayoutTransform. You should use RenderTransform instead, try changing the Setter Property as well as the Storyboard.TargetProperty to RenderTransform and it should work.
<Style x:Key="InvViewBoxStyle" TargetType="Viewbox">
<Setter Property="RenderTransform">
<Setter.Value>
<ScaleTransform />
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding IsChecked, ElementName=myCheckBox}" Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(ScaleTransform.ScaleY)" To="2" Duration="0:0:0.5" />
<DoubleAnimation Storyboard.TargetProperty="(RenderTransform).(ScaleTransform.ScaleY)" To="2" Duration="0:0:0.5" />
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
Also if you want to keep the LayoutTransform you can try changing your Grid to a Canvas, that might work too.
Your Grid is defining the space your ViewBoxes are allowed to occupy, so you should animate your Grid's properties, not your ViewBoxes.
You can either animate it's Height/Width, or apply a ScaleTransform to it.
Also, a LayoutTransform gets applied before rendering, while a RenderTransform gets applied afterwards. You might want to try using a RenderTransform instead of a Layout one with your existing code to see if it will all your ViewBoxes to expand outside of their allowed area.
I have done something similair to you this way (done in the code behind on a mouse over event):
DoubleAnimation animation = new DoubleAnimation();
animation.From = MenuBorder.Width;
animation.To = 170;
animation.Duration = new Duration(TimeSpan.FromMilliseconds(350));
MenuBorder.BeginAnimation(WidthProperty, animation);
Here i have a grid with a border inside. The grids with is set to automatic. Therefore it looks like it is the grid I am animating but it is really the border inside the grid I am animating.
You should add the Type to the animation:
<DoubleAnimation Storyboard.TargetProperty="(Grid.LayoutTransform).(ScaleTransform.ScaleX)" To="2" Duration="0:0:0.5" />
I would set the value of ScaleX explicitly at the control:
<ScaleTransform ScaleX="1" />
I think what you are trying to achieve is to change the width/height of the ViewBox, and then the content will Scale accordingly.

Animation from within DataTemplate

Below is the data template I'm using for a listbox's ItemTemplate. It shows some simple data, and a button, which ideally should animate a Popup, also contained within the DataTemplate. Unfortunately the whole thing blow up at runtime. The error says line 52 is wrong, which is:
<EventTrigger RoutedEvent="Button.Click">
Here's the whole DataTemplate. I've used this popup before, with the same exact content templates and even the same animation elsewhere. It's only blowing up when I try to put it into a DataTemplate. I assume the animation is having difficulty finding the right animation target - I'm hoping someone here would know more.
<DataTemplate x:Key="ItemTemplate2">
<Border Width="100" Height="100" BorderThickness="4" BorderBrush="Red">
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Price}"/>
<Popup x:Name="popupContent" IsOpen="True" Margin="10,0,0,0" Grid.Row="0" >
<Popup.Child>
<Thumb x:Name="thumbContent" DragDelta="Thumb_DragDelta" Width="0" Height="0">
<Thumb.Template>
<ControlTemplate>
<local:thumbTemplate Margin="0" x:Name="df" />
</ControlTemplate>
</Thumb.Template>
</Thumb>
</Popup.Child>
</Popup>
<Button Content="Show">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<BeginStoryboard.Storyboard>
<Storyboard x:Name="sbShowPopup">
<DoubleAnimation Duration="0:0:1" To="200" Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="popupContent" d:IsOptimized="True"/>
<DoubleAnimation Duration="0:0:1" To="80" Storyboard.TargetProperty="(FrameworkElement.Height)" Storyboard.TargetName="popupContent" d:IsOptimized="True"/>
</Storyboard>
</BeginStoryboard.Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
</StackPanel>
</Border>
</DataTemplate>
You may have used this before but not in Silverlight. The only supported value for RoutedEvent in Silverlight is "FrameworkElement.LoadedEvent".
You will need the BlendSDK to do this sort of thing in Silverlight.

Resources