WPF通过事件调用命令

35 wpf events command

是否可以通过WPF中的事件调用命令?

我有一个保存按钮,按下时调用一个命令,当你完成一个文本框的编辑后,它会被按下,它也会传递一个对象作为一个命令参数

 <Button Content="Save"  Command="{Binding DataContext.SaveQueueTimeCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" CommandParameter="{Binding}" />
Run Code Online (Sandbox Code Playgroud)

我理想的做法是调用此命令并在文本框失去焦点时将对象作为参数传递,而不是必须按下按钮,例如:

 <Button LostFocus="{Binding SaveQueueTimeCommand}" />
Run Code Online (Sandbox Code Playgroud)

并且仍以某种方式将对象作为参数传递.有没有办法在不使用代码的情况下实现这一点,因为我正在使用MVVM模式

谢谢你的时间

Tre*_*vor 66

最简单的方法是使用交互触发器.

<Grid xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SomeEvent">
            <i:InvokeCommandAction Command="{Binding Path=SomeCommand, Mode=OneWay}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Grid>
Run Code Online (Sandbox Code Playgroud)

为了后人的缘故,我添加了这个.

  • 请注意,http://schemas.microsoft.com/expression/2010/interactivity位于Blend SDK中包含的System.Windows.Interactivity.dll中. (6认同)

Ken*_*art 15

您可以使用附加的行为来实现此目的.Marlon Grech编写了附加命令行为库,以免给您带来麻烦.用法如下:

<Grid>
    <local:CommandBehaviorCollection.Behaviors>
        <local:BehaviorBinding Event="MouseRightButtonDown" Command="{Binding SomeCommand}" CommandParameter="A Command on MouseRightButtonDown"/>
    </local:CommandBehaviorCollection.Behaviors>
</Grid>
Run Code Online (Sandbox Code Playgroud)


And*_*ndy 3

恐怕我认为你想做的事情是不可能的。命令不是委托,因此您无法针对事件编写命令。我认为最好的选择是处理Button.LostFocus事件,然后从处理程序手动执行命令。

使用 MVVM 时将代码放在代码后面并没有什么问题,最好将其最小化并保留代码仅用于查看相关任务。我会将此代码称为相关视图,因此会发现将代码放在代码后面。