Tutorial :How to make add a fade-in/fade-out animation based on ViewModel property value?



Question:

I have a ViewModel which exposes the string property PageToolBarVisible which can be true or false:

private string _pageToolBarVisible;  public string PageToolBarVisible  {      get      {          return _pageToolBarVisible;      }        set      {          _pageToolBarVisible = value;          OnPropertyChanged("PageToolBarVisible");      }  }  

Then on my View I have this DataTrigger which displays or hides the toolbar accordingly:

<Style x:Key="PageToolBarStyle" TargetType="Border">      <Style.Triggers>          <DataTrigger Binding="{Binding PageToolBarVisible}" Value="false">              <Setter Property="Visibility" Value="Collapsed"/>          </DataTrigger>      </Style.Triggers>  </Style>    <Border Style="{StaticResource PageToolBarStyle}"      DockPanel.Dock="Bottom" Padding="5 5 5 0" Background="#eee">      <Grid Background="#eee">          ...      </Grid>  </Border>  

How do I now add an animation so that:

  • when the ViewModel Property is changed from true to false, the toolbar fades out
  • when the ViewModel Property is changed from false to true, the toolbar fades in

I assume I have to add something like this to my style, but I don't know how or where:

<BeginStoryboard>  <Storyboard>      <DoubleAnimation      Storyboard.TargetName="PageToolBar"      Storyboard.TargetProperty="(TextBlock.Opacity)"      From="0.0" To="1.0" Duration="0:0:3"/>  </Storyboard>  </BeginStoryboard>  


Solution:1

You can put the BeginStoryboard inside your DataTrigger.EnterActions

<DataTrigger Binding="{Binding PageToolBarVisible}" Value="false">      <DataTrigger.EnterActions>          <BeginStoryboard>              <Storyboard>                  <DoubleAnimation                  Storyboard.TargetName="PageToolBar"                  Storyboard.TargetProperty="(TextBlock.Opacity)"                  From="0.0" To="1.0" Duration="0:0:3"/>              </Storyboard>          </BeginStoryboard>      </DataTrigger.EnterActions>        <DataTrigger.ExitActions>          <BeginStoryboard>              <Storyboard>                  <DoubleAnimation                      Storyboard.TargetName="PageToolBar"                      Storyboard.TargetProperty="(TextBlock.Opacity)"                      From="1.0" To="0.0" Duration="0:0:3"/>              </Storyboard>          </BeginStoryboard>      </DataTrigger.ExitActions>  </DataTrigger>  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »