WPF MVVM DataGrid 按钮列的命令绑定

WPF DataGrid 按钮列 命令如何绑定鼠标按下与松开事件?如下并未成功,请懂的哥们指教。

                    <DataGridTemplateColumn Header="Jog-">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate DataType="model:AxisKeyValueItem">
                                <Button Content="Jog-" Width="60" Margin="5,0"  Style="{StaticResource ButtonPrimary}">
                                    <hc:Interaction.Triggers>
                                        <hc:EventTrigger EventName="MouseDown">
                                            <hc:EventToCommand Command="{Binding Path=DataContext.MoveJogReduceCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding }"></hc:EventToCommand>
                                        </hc:EventTrigger>
                                        <hc:EventTrigger EventName="MouseUp">
                                            <hc:EventToCommand Command="{Binding Path=DataContext.MoveStopCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding }"></hc:EventToCommand>
                                        </hc:EventTrigger>
                                    </hc:Interaction.Triggers>
                                </Button>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>


在WPF DataGrid中,要绑定按钮列的鼠标按下和松开事件,可以使用类似于您提供的代码来实现。用到了Interaction.Triggers和EventTrigger的功能。

根据您提供的代码,看起来已经使用了Interaction.Triggers和EventTrigger,但似乎没有完全正确地绑定鼠标按下和松开事件。

以下是修改后的示例代码,演示如何正确绑定鼠标按下和松开事件:

<DataGridTemplateColumn Header="Jog-">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate DataType="model:AxisKeyValueItem">
<Button Content="Jog-" Width="60" Margin="5,0" Style="{StaticResource ButtonPrimary}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewMouseDown">
<i:InvokeCommandAction Command="{Binding Path=DataContext.MoveJogReduceCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding }"/>
</i:EventTrigger>
<i:EventTrigger EventName="PreviewMouseUp">
<i:InvokeCommandAction Command="{Binding Path=DataContext.MoveStopCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding }"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>


请注意,上述示例中使用了i:前缀,这需要将命名空间xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"添加到XAML页面的根元素。

修改后的代码将鼠标按下和松开事件更改为PreviewMouseDownPreviewMouseUp,这是WPF中预览事件的常用命名。另外,还将Interaction.Triggers更改为i:Interaction.Triggers,并使用i:InvokeCommandAction来触发命令。

通过这样的修改,现在按钮列将正确绑定鼠标按下和松开事件,并将对应的命令触发,并传递绑定的对象作为命令参数。