如何根据ViewModel属性值添加淡入/淡出动画?

时间:2009-07-07 12:16:18

标签: wpf xaml animation mvvm triggers

我有一个 ViewModel ,它会公开字符串属性 PageToolBarVisible ,可以是 true false

private string _pageToolBarVisible;
public string PageToolBarVisible
{
    get
    {
        return _pageToolBarVisible;
    }

    set
    {
        _pageToolBarVisible = value;
        OnPropertyChanged("PageToolBarVisible");
    }
}

然后在我的查看上,我有 DataTrigger 显示隐藏相应的工具栏:

<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>

我现在如何添加 动画以便:

  • 当ViewModel属性从 true更改为false 时,工具栏淡出
  • 当ViewModel属性从 false更改为true 时,工具栏淡入

我认为我必须在我的风格中添加这样的东西,但我不知道如何或在哪里:

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

1 个答案:

答案 0 :(得分:14)

您可以将BeginStoryboard放在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>