【问题标题】:Achieve "slide down" animation in WPF在 WPF 中实现“向下滑动”动画
【发布时间】:2012-01-03 12:11:21
【问题描述】:

我正在尝试为Expander 控件创建自己的模板。当控件展开时,我希望内容慢慢向下滑动。

在编译时不知道所需的内容高度。

我认为我们可以将向下滑动定义为动画:

<Storyboard x:Key="ExpandContent">

    <DoubleAnimation 
        Storyboard.TargetName="_expanderContent" 
        Storyboard.TargetProperty="Height" 
        From="0.0" 
        To="{Binding ElementName=_expanderContent,Path=DesiredHeight}"
        Duration="0:0:1.0" />
</Storyboard>

但不幸的是没有。我们得到一个错误

无法冻结此 Storyboard 时间线树以供跨线程使用。

似乎我们在定义动画参数时不能使用绑定。 (也在this question 中讨论过。)

有人对我如何解决这个问题有任何想法吗?我对使用LayoutTransform.ScaleY 持谨慎态度,因为那样会造成图像失真。

这类似于this question,但这个问题的答案涉及编写代码隐藏,我认为这在控制模板中是不可能的。 我想知道基于 XAML 的解决方案是否可行。


对于它的价值,这是我的控制模板的当前状态。
<ControlTemplate x:Key="ExpanderControlTemplate"  TargetType="{x:Type Expander}">
    <ControlTemplate.Resources>
            <!-- Here are the storyboards which don't work -->
            <Storyboard x:Key="ExpandContent">

                <DoubleAnimation 
                    Storyboard.TargetName="_expanderContent" 
                    Storyboard.TargetProperty="Height" 
                    From="0.0" 
                    To="{Binding ElementName=_expanderContent,Path=DesiredHeight}"
                    Duration="0:0:1.0" />
            </Storyboard>
            <Storyboard x:Key="ContractContent">

                <DoubleAnimation 
                    Storyboard.TargetName="_expanderContent" 
                    Storyboard.TargetProperty="Height" 
                    From="{Binding ElementName=_expanderContent,Path=DesiredHeight}"
                    To="0.0"
                    Duration="0:0:1.0" />

            </Storyboard>
        </ControlTemplate.Resources>
    <Grid Name="MainGrid" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Name="ContentRow" Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Border>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>
                <ContentPresenter ContentSource="Header" />
                <ToggleButton Template="{StaticResource ProductButtonExpand}"
                              Grid.Column="1"
                              IsChecked="{Binding Path=IsExpanded,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}" 
                              />
                <Rectangle Grid.ColumnSpan="2" Fill="#FFDADADA" Height="1" Margin="8,0,8,2" VerticalAlignment="Bottom"/>

            </Grid>
        </Border>

            <ContentPresenter Grid.Row="1" HorizontalAlignment="Stretch" Name="_expanderContent">

            </ContentPresenter>

    </Grid>
    <ControlTemplate.Triggers>
        <Trigger Property="IsExpanded" Value="True">
            <Setter TargetName="_expanderContent" Property="Height" Value="{Binding ElementName=_expanderContent,Path=DesiredHeight}" />

                <!-- Here is where I would activate the storyboard if they did work -->
                <Trigger.EnterActions>
                <!--<BeginStoryboard Storyboard="{StaticResource ExpandContent}"/>-->
            </Trigger.EnterActions>
                <Trigger.ExitActions>
                    <!--<BeginStoryboard x:Name="ContractContent_BeginStoryboard" Storyboard="{StaticResource ContractContent}"/>-->
                </Trigger.ExitActions>
        </Trigger>
            <Trigger Property="IsExpanded" Value="False">

                <Setter TargetName="_expanderContent" Property="Height" Value="0" />
            </Trigger>
        </ControlTemplate.Triggers>

</ControlTemplate>

【问题讨论】:

  • 为什么将 ToFrom 设置为 DesiredHight?如果您不设置它们,无论如何都会自动完成。

标签: wpf animation controltemplate


【解决方案1】:

有一个即用型且仅限 XAML 的解决方案on CodeProject

风格:

    <local:MultiplyConverter x:Key="MultiplyConverter" />
    <Style TargetType="Expander" x:Key="VerticalSlidingEmptyExpander">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Expander}">
                    <ScrollViewer x:Name="ExpanderContentScrollView"
                  HorizontalScrollBarVisibility="Hidden"
                  VerticalScrollBarVisibility="Hidden"
                  HorizontalContentAlignment="Stretch"
                  VerticalContentAlignment="Top"
                  >
                        <ScrollViewer.Tag>
                            <system:Double>0.0</system:Double>
                        </ScrollViewer.Tag>
                        <ScrollViewer.Height>
                            <MultiBinding Converter="{StaticResource MultiplyConverter}">
                                <Binding Path="ActualHeight" ElementName="ExpanderContent"/>
                                <Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
                            </MultiBinding>
                        </ScrollViewer.Height>
                        <ContentPresenter x:Name="ExpanderContent" ContentSource="Content"/>
                    </ScrollViewer>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsExpanded" Value="True">
                            <Trigger.EnterActions>
                                <BeginStoryboard>
                                    <Storyboard>
                                        <DoubleAnimation 
                       Storyboard.TargetName="ExpanderContentScrollView"
                       Storyboard.TargetProperty="Tag"
                       To="1"
                       Duration="0:0:0.2"/>
                                    </Storyboard>
                                </BeginStoryboard>
                            </Trigger.EnterActions>
                            <Trigger.ExitActions>
                                <BeginStoryboard>
                                    <Storyboard>
                                        <DoubleAnimation 
                         Storyboard.TargetName="ExpanderContentScrollView"
                         Storyboard.TargetProperty="Tag"
                         To="0"
                         Duration="0:0:0.2"/>
                                    </Storyboard>
                                </BeginStoryboard>
                            </Trigger.ExitActions>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style TargetType="Expander" x:Key="HorizontalSlidingEmptyExpander">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Expander}">
                    <ScrollViewer x:Name="ExpanderContentScrollView"
                  HorizontalScrollBarVisibility="Hidden"
                  VerticalScrollBarVisibility="Hidden"
                  HorizontalContentAlignment="Left"
                  VerticalContentAlignment="Stretch"
                  >
                        <ScrollViewer.Tag>
                            <system:Double>0.0</system:Double>
                        </ScrollViewer.Tag>
                        <ScrollViewer.Width>
                            <MultiBinding Converter="{StaticResource MultiplyConverter}">
                                <Binding Path="ActualWidth" ElementName="ExpanderContent"/>
                                <Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
                            </MultiBinding>
                        </ScrollViewer.Width>
                        <ContentPresenter x:Name="ExpanderContent" ContentSource="Content"/>
                    </ScrollViewer>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsExpanded" Value="True">
                            <Trigger.EnterActions>
                                <BeginStoryboard>
                                    <Storyboard>
                                        <DoubleAnimation 
                       Storyboard.TargetName="ExpanderContentScrollView"
                       Storyboard.TargetProperty="Tag"
                       To="1"
                       Duration="0:0:0.2"/>
                                    </Storyboard>
                                </BeginStoryboard>
                            </Trigger.EnterActions>
                            <Trigger.ExitActions>
                                <BeginStoryboard>
                                    <Storyboard>
                                        <DoubleAnimation 
                         Storyboard.TargetName="ExpanderContentScrollView"
                         Storyboard.TargetProperty="Tag"
                         To="0"
                         Duration="0:0:0.2"/>
                                    </Storyboard>
                                </BeginStoryboard>
                            </Trigger.ExitActions>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

乘法转换器:

public class MultiplyConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType,
           object parameter, CultureInfo culture)
    {
        double result = 1.0;
        for (int i = 0; i < values.Length; i++)
        {
            if (values[i] is double)
                result *= (double)values[i];
        }

        return result;
    }

    public object[] ConvertBack(object value, Type[] targetTypes,
           object parameter, CultureInfo culture)
    {
        throw new Exception("Not implemented");
    }
}

我将样式复制为水平和垂直版本,并省略了切换按钮,但您可以从原始帖子中轻松获得。

【讨论】:

  • 使用这个解决方案的问题是没有切换按钮,也没有标题
【解决方案2】:

如果你可以使用InteractionsFluidLayout (Blend 4 SDK) 你很幸运,它对于那些花哨的动画真的很有用。

先设置内容CP的Height为0:

<ContentPresenter Grid.Row="1"
    HorizontalAlignment="Stretch"
    x:Name="_expanderContent"
    Height="0"/>

要对此进行动画处理,只需将NaN 中的NaN 动画化为代表展开状态的NaN(非离散动画不允许您使用NaN):

xmlns:is="http://schemas.microsoft.com/expression/2010/interactions"
<Grid x:Name="MainGrid" Background="White">
    <VisualStateManager.CustomVisualStateManager>
        <is:ExtendedVisualStateManager/>
    </VisualStateManager.CustomVisualStateManager>
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="ExpansionStates" is:ExtendedVisualStateManager.UseFluidLayout="True">
            <VisualStateGroup.Transitions>
                <VisualTransition GeneratedDuration="0:0:1"/>
            </VisualStateGroup.Transitions>
            <VisualState x:Name="Expanded">
                <Storyboard>
                    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Height)"
                                                   Storyboard.TargetName="_expanderContent">
                        <DiscreteDoubleKeyFrame KeyTime="0" Value="NaN"/>
                    </DoubleAnimationUsingKeyFrames>
                </Storyboard>
            </VisualState>
            <VisualState x:Name="Collapsed"/>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    <!-- ... --->

这应该是所有必要的,流畅的布局将从那里为您创建过渡。


如果您有一个很好的代码隐藏解决方案,您甚至可以在字典中使用代码隐藏,如下所示:

<!-- TestDictionary.xaml -->
<ResourceDictionary x:Class="Test.TestDictionary"
                    ...>
//TestDictionary.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace Test
{
    partial class TestDictionary : ResourceDictionary
    {
        //Handlers and such here
    }
}

【讨论】:

  • 这个解决方案根本行不通。 NaN 仍然被抱怨。
【解决方案3】:

这是一个老问题,但我今天遇到了问题,所以我想发布我的解决方案是值得的:

我必须为网格行的 Height 属性设置动画(上下滑动),但需要动态绑定,以便该行再次滑动到与之前相同的位置。

我发现这个答案非常有帮助(在与 XAML 毫无结果的斗争之后): http://go4answers.webhost4life.com/Question/found-solution-work-protected-override-190845.aspx

有时在代码隐藏中做事更简单:

        Storyboard sb = new Storyboard();

        var animation = new GridLengthAnimation
        {
                Duration = new Duration(500.Milliseconds()),
                From = this.myGridRow.Height,
                To = new GridLength(IsGridRowVisible ? GridRowPreviousHeight : 0, GridUnitType.Pixel)
        };

        // Set the target of the animation
        Storyboard.SetTarget(animation, this.myGridRow);
        Storyboard.SetTargetProperty(animation, new PropertyPath("Height"));

        // Kick the animation off
        sb.Children.Add(animation);
        sb.Begin();

GridLengthAnimation 类可以在这里找到: http://social.msdn.microsoft.com/forums/en-US/wpf/thread/da47a4b8-4d39-4d6e-a570-7dbe51a842e4/

【讨论】:

  • 非常感谢!最后我让我的参数化动画工作了。确实,这在 XAML 中似乎是不可能的。
  • 很高兴这有帮助。是的,需要一段时间才能了解 WPF 中的哪些事情在 XAML 中太麻烦了,反之亦然;)
  • 干得好!比做同样事情所需的所有 XAML 技巧要容易得多。对于所有 MVVM “没有代码背后”的狂热分子,这都是 UI-Only 代码 - 克服它。
  • 用 XAML 拯救我的一天。谢谢@SverrirSigmundarson
猜你喜欢
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-21
  • 2013-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多