2017-07-17 70 views
0

我有一个Silverlight应用程序,它使用带有TabControl的窗体。如何将TabItem GotFocus绑定到ViewModel命令

我想有一个TabItem GotFocus事件绑定到我的ViewModel。不过,我在执行以下操作时遇到错误。

<controls:TabControl> 
    <controls.TabItem GotFocus="{Binding Model.MyGotFocusCommand}"> 

我可以将TabControl事件绑定到我的ViewModel吗?

+0

看看这里:https://stackoverflow.com/questions/16659592/give-a-tabitem-focus-when-dynamically-adding-using-mvvm –

+0

'Model.MyGotFocusCommand'好吧,这是一个代码味道。在你的模型和视图模型中嵌入UI逻辑,呃? – Will

回答

1

您不能直接将事件绑定到命令。在事件上调用命令需要使用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> 

最后但并非最不重要,我经常能接受简单地赶在代码中的事件背后,并从那里我的路线到我的视图模型。如果你能忍受这些缺点(主要是可测试性的丧失),那么这种方法很简单直接。

相关问题