【发布时间】:2012-12-28 04:41:19
【问题描述】:
我有一个应该最小化的面板,除非用户将鼠标悬停在面板上。它是使用故事板实现的,当用户将鼠标放在控件上时,该故事板可以增加面板的高度。目前目标高度被硬编码为 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添加边距。您甚至可以使用多值转换器,这样您也可以绑定边距,而不必硬编码软糖因子。最后,您可以将堆栈面板包装在另一个面板中(没有边距)并绑定到该面板的高度。 -
"将您的堆栈面板包装在另一个面板中(没有边距)" :-D 使用@MattBurland 的明显建议解决了问题,至少现在
-
很高兴有帮助。我会将我的评论转化为答案,以便您将问题标记为已回答。