C# 如何将TabItem GotFocus绑定到ViewModel comand
我有一个silverlight应用程序,它使用带有TabControl的表单 我想将其中一个TabItem GotFocus事件绑定到我的ViewModel。但是,当我执行以下操作时,会出现错误C# 如何将TabItem GotFocus绑定到ViewModel comand,c#,silverlight,mvvm,C#,Silverlight,Mvvm,我有一个silverlight应用程序,它使用带有TabControl的表单 我想将其中一个TabItem GotFocus事件绑定到我的ViewModel。但是,当我执行以下操作时,会出现错误 <controls:TabControl> <controls.TabItem GotFocus="{Binding Model.MyGotFocusCommand}"> 我可以将选项卡Control events绑定到我的ViewModel吗?不能将事件直接绑定到命令
<controls:TabControl>
<controls.TabItem GotFocus="{Binding Model.MyGotFocusCommand}">
我可以将选项卡Control events绑定到我的ViewModel吗?不能将事件直接绑定到命令。对事件调用命令需要使用表达式混合交互触发器 添加对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 Blend,可以使用允许通过行为绑定的框架(例如MVVM Light)。这是通过EventToCommand类公开的行为,允许您将事件绑定到命令。这样,在引发事件时,将像调用事件处理程序一样调用绑定命令
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<cmd:EventToCommand Command="{Binding Mode=OneWay,Path=GotFocusCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
最后但并非最不重要的一点是,我经常发现在代码中捕获事件是可以接受的,并从那里将其路由到视图模型中。如果您能够克服这些缺点(主要是失去可测试性),那么这种方法简单明了。您无法将事件直接绑定到命令。对事件调用命令需要使用表达式混合交互触发器 添加对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 Blend,可以使用允许通过行为绑定的框架(例如MVVM Light)。这是通过EventToCommand类公开的行为,允许您将事件绑定到命令。这样,在引发事件时,将像调用事件处理程序一样调用绑定命令
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<cmd:EventToCommand Command="{Binding Mode=OneWay,Path=GotFocusCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
最后但并非最不重要的一点是,我经常发现在代码中捕获事件是可以接受的,并从那里将其路由到视图模型中。如果你能忍受缺点(主要是失去可测试性),那么这种方法简单明了。看看这里:
Model.MyGotFocusCommand
好吧,这是一种代码味道。将UI逻辑塞进模型和视图模型中,嗯?看看这里:Model.MyGotFocusCommand
嗯,这是一种代码味道。把用户界面逻辑塞进你的模型和视图模型,嗯?