我正在嘗試使用附加事件來呼叫ICommand.
我正在使用Microsoft.Toolkit.MvvmNuGet 包以及Microsoft.Xaml.Behaviors.WpfNuget 包。
我已經成功使用開始故事板<BeginStoryBoardAction />內<FOO.Triggers />通過定義<EventTrigger />和設定RoutedEvent等于有問題的附加事件的名稱。
但是,據我所知,沒有辦法呼叫ICommandusing 中提供的任何內容<EventTrigger />。我的意思是,我不能在<EventTriggers.Actions />塊的主體內使用任何東西(類似于<Behaviors.InvokeCommandAction />),這將導致ICommand被呼叫。
根據最小、完整和可驗證示例,為了演示我想要實作的目標,您可以參考 GitHub 上的專案 - https://github.com/AbbottWC/MCVE_AttachedEventFailure。
或者
打開 Visual Studio。創建 WPF 應用程式(針對 .Net Core 3.1)
工具 -> NuGet 包管理器 -> 管理此解決方案的包
添加 Microsoft.Toolkit.Mvvm(用于
RelayCommand類)和Microsoft.Xaml.Behaviors.Wpf包。在里面
App.Xaml.csprivate 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將以下內容添加到 XAML 正文的結束
</Window>標記之前:
<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>
所以重申我的問題,我想在這里實作的目標是可能的嗎?難道不能以這種方式使用附加事件嗎?
謝謝。
uj5u.com熱心網友回復:
據我了解,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 -附加事件/
基本上,你繼承EventTriggerBase<T>,并在OnAttached您需要呼叫方法AddHandler對您AssociatedObject添加事件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/337954.html
