是否有可能使用调用命令使用附带事件的Microsoft.Xaml.Behaviors.EventTrigger ?<



我正在尝试使用附加事件来调用ICommand

我正在使用Microsoft.Toolkit.MvvmNuGet包,以及Microsoft.Xaml.Behaviors.WpfNuGet包。

通过定义<EventTrigger />并设置RoutedEvent等于所附事件的名称,我已经成功地在<FOO.Triggers />中使用<BeginStoryBoardAction />启动了一个故事板。

然而,据我所知,没有办法使用<EventTrigger />中提供的任何东西来调用ICommand。我的意思是,我不能在<EventTriggers.Actions />块(类似于<Behaviors.InvokeCommandAction />)的主体内使用任何会导致ICommand被调用的内容。

符合最小,完整和可验证的示例,以演示我想要实现的目标,您可以参考GitHub上的项目- https://github.com/AbbottWC/MCVE_AttachedEventFailure。

  • 打开Visual Studio。创建一个WPF应用程序(针对。net Core 3.1)

  • 工具→NuGet Package Manager ->管理此解决方案的包

  • 添加Microsoft.Toolkit.Mvvm(用于RelayCommand类)和Microsoft.Xaml.Behaviors.Wpf包。

  • App.Xaml.cs

    private RelayCommand testCommand = new RelayCommand(( ) => MessageBox.Show("Event Captured!", "Success!"));
    public RelayCommand TestCommand => testCommand;
    
  • 在MainWindow.xaml

  • 定义命名空间xmlns:i="http://schemas.microsoft.com/xaml/behaviors"

  • local重命名为l

  • 在结束</Window>标记之前将以下内容添加到XAML正文中:

<i:Interaction.Triggers>
<!--This will work, and is present only to prove the problem lies not with the Command or how it is being accessed.-->
<i:EventTrigger EventName="MouseEnter">
<i:EventTrigger.Actions>
<i:InvokeCommandAction Command="{Binding TestCommand, Source={x:Static l:App.Current}}" />
</i:EventTrigger.Actions>
</i:EventTrigger>
<!--This will not work, and is meant to provide an example of the problem.-->
<i:EventTrigger EventName="Mouse.MouseEnter">
<i:EventTrigger.Actions>
<i:InvokeCommandAction Command="{Binding TestCommand, Source={x:Static l:App.Current}}" />
</i:EventTrigger.Actions>
</i:EventTrigger>
</i:Interaction.Triggers>

所以重申一下我的问题,我在这里想要达到的是可能的吗?是否不可能以这种方式使用附加事件?

谢谢。

据我所知,EventTrigger只能监听源对象"拥有"的事件。所以回答你的问题,这是不可能使用EventTrigger类。

如果您查看源代码,当您传递Mouse.MouseEnter时,它会尝试从目标类型获取该事件。另外,由于您没有指定目标,它默认为AssociatedObject,在您的示例中是Window

Type targetType = obj.GetType();
EventInfo eventInfo = targetType.GetEvent(eventName);

现在我发现的问题是,如果它找不到事件,它只会在源对象不为空时抛出异常,而在您的情况下,您没有指定一个,因此它会默默地失败。不知道为什么设计师要这样做。

现在,我确实找到了这篇博客文章,它描述了如何解决这个问题:https://sergecalderara.wordpress.com/2012/08/23/how-to-attached-an-mvvm-eventtocommand-to-an-attached-event/

基本上,您继承了EventTriggerBase<T>,在OnAttached方法中,您需要在AssociatedObject上调用AddHandler来添加事件。

最新更新