您不能直接將事件綁定到命令。在事件上調用命令需要使用Expression Blend交互觸發器。
添加對Microsoft.Expression.Interactions.dll和System.Windows.Interactivity.dll程序集的引用。
聲明視圖中的交互和互動空間前綴:
的xmlns:I = 「http://schemas.microsoft.com/expression/2010/interactivity」 的xmlns:EI =「HTTP:// schemas.microsoft.com/expression/2010/interactions」
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<i:InvokeCommandAction
Command="{Binding GotFocusCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
如果你不喜歡使用expression混合,你可以用一個框架(如MVVM光)允許通過行爲結合去。這是通過EventToCommand類公開的行爲,允許您將事件綁定到命令。這樣,當事件被引發時,綁定命令就像事件處理程序一樣被調用。
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<cmd:EventToCommand Command="{Binding Mode=OneWay,Path=GotFocusCommand}"
PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
最後但並非最不重要,我經常能接受簡單地趕在代碼中的事件背後,並從那裏我的路線到我的視圖模型。如果你能忍受這些缺點(主要是可測試性的喪失),那麼這種方法很簡單直接。
看看這裏:https://stackoverflow.com/questions/16659592/give-a-tabitem-focus-when-dynamically-adding-using-mvvm –
'Model.MyGotFocusCommand'好吧,這是一個代碼味道。在你的模型和視圖模型中嵌入UI邏輯,呃? – Will