43

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

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

 <Button Content="Save"  Command="{Binding DataContext.SaveQueueTimeCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" CommandParameter="{Binding}" />

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

 <Button LostFocus="{Binding SaveQueueTimeCommand}" />

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

谢谢你的时间

4

4 回答 4

76

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

<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>

为了后代,我添加了这个。

于 2014-02-21T18:45:13.007 回答
16

您可以使用附加行为来实现此目的。Marlon Grech编写了附加命令行为库来为您省去麻烦。用法如下所示:

<Grid>
    <local:CommandBehaviorCollection.Behaviors>
        <local:BehaviorBinding Event="MouseRightButtonDown" Command="{Binding SomeCommand}" CommandParameter="A Command on MouseRightButtonDown"/>
    </local:CommandBehaviorCollection.Behaviors>
</Grid>
于 2009-06-26T12:06:54.033 回答
3

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

使用 MVVM 时把代码放在后面的代码没有什么问题,最好是尽量减少代码,只保留查看相关任务的代码。我将此代码视图称为相关,因此将代码放在后面的代码中。

于 2009-06-26T11:06:12.083 回答
2
<Grid MouseRightButtonDown ="{eb:EventBinding Command=SomeCommand, CommandParameter=$e}">

</Grid>

命令

{eb:EventBinding} (Simple naming pattern to find Command)

{eb:EventBinding Command=CommandName}

命令参数

$e (EventAgrs) 

$this or $this.Property

string

https://github.com/JonghoL/EventBindingMarkup

于 2014-11-20T02:39:37.947 回答