[英]WPF calling commands via events
是否可以通过WPF中的事件调用命令?
我有一个保存按钮,当按下该按钮时会调用命令,当您完成文本框的编辑时会按下该按钮,它还会将对象作为命令参数传递
<Button Content="Save" Command="{Binding DataContext.SaveQueueTimeCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" CommandParameter="{Binding}" />
我理想地想做的是调用此命令,并在文本框失去焦点时将该对象作为参数传递,而不必按下按钮,例如:
<Button LostFocus="{Binding SaveQueueTimeCommand}" />
而且仍然以某种方式将对象作为参数传递。 有没有一种方法可以实现此目的而无需在后面使用代码,因为我正在使用MVVM模式
谢谢你的时间
最简单的方法是使用交互触发器。
<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>
为了后代,我添加了此内容。
您可以使用附加行为来实现此目的。 Marlon Grech编写了“ 附加命令行为”库来为您节省麻烦。 用法如下所示:
<Grid>
<local:CommandBehaviorCollection.Behaviors>
<local:BehaviorBinding Event="MouseRightButtonDown" Command="{Binding SomeCommand}" CommandParameter="A Command on MouseRightButtonDown"/>
</local:CommandBehaviorCollection.Behaviors>
</Grid>
恐怕我认为您想做的事是不可能的。 命令不是委托,因此您不能为事件编写命令。 我认为您最好的选择是处理Button.LostFocus
事件,然后从处理程序中手动执行命令。
使用MVVM时,将代码放在代码中没有任何问题,最好是将其最小化并保留代码以仅查看相关任务。 我将此代码视图称为相关视图,因此可以将代码放在代码后面。
<Grid MouseRightButtonDown ="{eb:EventBinding Command=SomeCommand, CommandParameter=$e}">
</Grid>
命令
{eb:EventBinding} (Simple naming pattern to find Command)
{eb:EventBinding Command=CommandName}
CommandParameter
$e (EventAgrs)
$this or $this.Property
string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.