XAML动画的高度控制与动态内容



我有一个应该最小化的面板,除非用户将鼠标悬停在面板上。它是使用一个故事板实现的,当用户将鼠标放在控件上时,该故事板允许面板的高度增长。目前,目标高度硬编码为400,这是一个糟糕的解决方案,因为每次应用程序启动时面板的内容都会不同(在执行期间它是静态的)。

如何创建一个动画,让面板增长到当前内容的大小?

<Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="500" Width="525">
<Grid>
    <Border Margin="10,0" Background="LightGray" HorizontalAlignment="Left" VerticalAlignment="Top" CornerRadius="0,0,8,8">
        <Border.Effect>
            <DropShadowEffect Opacity="0.5"/>
        </Border.Effect>
        <Border.Triggers>
            <EventTrigger RoutedEvent="Border.MouseEnter">
                <BeginStoryboard>
                    <BeginStoryboard.Storyboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetProperty="Height" 
                                             From="25" 
                                             To="400" 
                                             Duration="0:0:0.2" />
                        </Storyboard>
                    </BeginStoryboard.Storyboard>
                </BeginStoryboard>
            </EventTrigger>
            <EventTrigger RoutedEvent="Border.MouseLeave">
                <BeginStoryboard>
                    <BeginStoryboard.Storyboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetProperty="Height" 
                                             From="400" 
                                             To="25" 
                                             Duration="0:0:0.2" />
                        </Storyboard>
                    </BeginStoryboard.Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Border.Triggers>
        <StackPanel Margin="5">
            <TextBlock Height="25" Text="My items panel" />
            <ListBox MinWidth="150" MinHeight="100" ItemsSource="{Binding MyItems}" />
        </StackPanel>
    </Border>
</Grid>

编辑:我已经尝试绑定到StackPanel的高度,但这并没有真正帮助,因为它没有考虑到StackPanel的边距,从而使面板比需要的短。

<DoubleAnimation Storyboard.TargetProperty="Height" 
                 From="{Binding ElementName=NameOfStackPanel, Path=ActualHeight}"
                 To="25" 
                 Duration="0:0:0.2" />

你可以创建一个转换器来处理添加边距到你的StackPanel的ActualHeight。您甚至可以使用多值转换器,这样您也可以绑定页边距,而不必硬编码软糖因子。最后,你可能会把你的stackpanel包裹在另一个面板中(没有边距),并绑定到那个面板的高度。

最新更新