WPF 通过事件调用命令 [英] WPF calling commands via events
问题描述
是否可以通过 WPF 中的事件调用命令?
Is it possible to call a command via an event in WPF?
我有一个保存按钮,按下它会调用一个命令,当你完成编辑一个文本框时按下这个按钮,它还传递一个对象作为命令参数
I have a save button that when pressed calls a command, this is pressed when you have finished editing a textbox, it also passes an object as a command parameter
<Button Content="Save" Command="{Binding DataContext.SaveQueueTimeCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" CommandParameter="{Binding}" />
我最理想的做法是在文本框失去焦点时调用此命令并将对象作为参数传递,而不必按下按钮,例如:
What I would ideally like to do is call this command and pass the object as a parameter when the textbox loses focus, rather than having to press the button, something like:
<Button LostFocus="{Binding SaveQueueTimeCommand}" />
并且仍然以某种方式将对象作为参数传递.有没有一种方法可以在不使用代码的情况下实现这一点,因为我正在使用 MVVM 模式
And still somehow pass the object as a parameter. Is there a way to acheive this without using code behind as I am using the MVVM pattern
感谢您的时间
推荐答案
最简单的方法是使用交互触发器.
The simplest way to do this is using an interaction trigger.
<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>
为了后人的缘故,我添加了这个.
I have added this for posterity sake.
这篇关于WPF 通过事件调用命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!