我在使用 EventTriggers 时遇到问题。我有两个按钮和两个 EventTrigger,我想从这些按钮中监听 Click 事件,然后触发器应该启动一个 StoryBoard,它会为控件的高度设置动画。
我在启动 StoryBoards 时没有问题,我只是在指定 EventTrigger 的 SourceName 时遇到了问题:
<UserControl x:Class="MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
>
<UserControl.Resources>
<Storyboard x:Key="GrowPanel1">
<DoubleAnimation To="400" Duration="0:0:0.75" Storyboard.TargetName="Panel1" Storyboard.TargetProperty="Height" />
</Storyboard>
<Storyboard x:Key="GrowPanel2">
<DoubleAnimation To="400" Duration="0:0:0.75" Storyboard.TargetName="Panel2" Storyboard.TargetProperty="Height" />
</Storyboard>
</UserControl.Resources>
<Grid >
<Grid.Triggers>
<EventTrigger RoutedEvent="Button.Click" SourceName="TriggerElement1" >
<EventTrigger.Actions>
<BeginStoryboard Storyboard="{StaticResource GrowPanel1}" />
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="Button.Click" SourceName="TriggerElement2" >
<EventTrigger.Actions>
<BeginStoryboard Storyboard="{StaticResource GrowPanel2}" />
</EventTrigger.Actions>
</EventTrigger>
</Grid.Triggers>
<Border BorderBrush="HotPink" BorderThickness="2">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ContentPresenter Panel.ZIndex="20" Grid.Column="1" >
<ContentPresenter.Content>
<StackPanel Orientation="Horizontal">
<Button x:Name="TriggerElement2" Background="BurlyWood" Width="30" Height="30" VerticalAlignment="Top" />
<Button x:Name="TriggerElement1" Background="Chartreuse" Width="30" Height="30" VerticalAlignment="Top" />
</StackPanel>
</ContentPresenter.Content>
</ContentPresenter>
<Grid Grid.Column="0" Grid.ColumnSpan="2">
<my1:TreeViewNav Name="Panel1" Height="0" VerticalAlignment="Top" />
<my:ListViewNav x:Name="Panel2" Height="0" VerticalAlignment="Top" />
</Grid>
</Grid>
</Border>
</Grid>
</UserControl>
有了这个我得到一个运行时错误:
最可能导致的异常是:'System.Windows.Markup.XamlParseException: 'System.Windows.Controls.Grid' 的初始化引发了异常。行号“23”和行位置“6”。---> System.ArgumentException:找不到名为“TriggerElement1”的 FrameworkElement。在 System.Windows.FrameworkElement.FindNamedFrameworkElement(FrameworkElement startElement, String targetName) 在 System.Windows.EventTrigger.ProcessOneTrigger(FrameworkElement triggersHost, TriggerBase triggerBase) 在 System.Windows.EventTrigger.ProcessTriggerCollection(FrameworkElement triggersHost) 在 System.Windows.FrameworkElement.TryFireInitialized () 在 System.Windows.FrameworkElement.EndInit() 在 MS.Internal.Xaml.Runtime.ClrObjectRuntime.InitializationGuard(XamlType xamlType,
删除 EventTrigger SourceName 属性可修复错误,但我需要根据单击的按钮启动不同的 StoryBoards。据我所知,我需要使用 SourceName。
为什么 WPF 找不到我的 Button 调用TriggerElement1
?我认为 RoutedEvents 会在视觉树中冒泡,所以只要触发器处于足够高的级别,它就应该没有命名问题?找到名为 Panel1 的 StoryBoard.Target 没有问题。我是否采取了正确的方法来获得两个按钮来触发不同的故事板?