c# - 如何将 TabItem GotFocus 绑定(bind)到 ViewModel 命令

标签 c# silverlight mvvm

我有一个使用带有 TabControl 的表单的 silverlight 应用程序。

我想让 TabItem GotFocus 事件之一绑定(bind)到我的 ViewModel。但是,当我执行以下操作时出现错误。

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

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

最佳答案

您不能将事件直接绑定(bind)到命令。对事件调用命令需要使用 Expression Blend 交互触发器。
添加对 Microsoft.Expression.Interactions.dll 和 System.Windows.Interactivity.dll 程序集的引用。
在您的 View 中声明交互和交互命名空间前缀:

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,您可以使用允许通过行为进行绑定(bind)的框架(例如 MVVM Light)。这通过 EventToCommand 类公开为允许您将事件绑定(bind)到命令的行为。这样,在引发事件时,将像事件处理程序一样调用绑定(bind)命令。
<i:Interaction.Triggers>
    <i:EventTrigger EventName="GotFocus">
        <cmd:EventToCommand Command="{Binding Mode=OneWay,Path=GotFocusCommand}" PassEventArgsToCommand="True" />
    </i:EventTrigger>
</i:Interaction.Triggers>
最后但并非最不重要的一点是,我经常发现在后面的代码中简单地捕获事件并从那里将其路由到我的 View 模型中是可以接受的。如果您可以忍受缺点(主要是可测试性的损失),那么该方法就简单明了。

关于c# - 如何将 TabItem GotFocus 绑定(bind)到 ViewModel 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45152668/

相关文章:

c# - 使用 BackgroundAgent 时程序集丢失

mvvm - KnockOutJS - 单个 View 中的多个 View 模型

c# - 带有 ICollectionView SortDescription 的数据网格丢失了 - 错误?

c# - Mono 中的 IEnumerable 接口(interface)和 Skip 方法

c# - 2d 平台游戏敌人运动

Silverlight渗透率

c# - "tons"点的 Web 图表?

wpf - 使用 FSharp.ViewModule 关闭对话框

c# - DbContext 已被处置(ASP.NET MVC)

c# - 是否有任何与word文档相关的元数据?