C# WPF MVVM中如何让DataGrid双击与回车触发同一命令?
Great question! You don’t have to duplicate the entire command parameter setup—there’s a cleaner, maintainable way to reuse your existing MultiBinding logic while adding the Enter key trigger, all while staying true to MVVM principles.
Optimal Approach: Reuse the MultiBinding as a Resource
The best practice here is to extract your MultiBinding into a reusable resource. This keeps your code DRY (Don’t Repeat Yourself) so if you ever need to adjust the parameters or converter, you only make the change once.
Here’s how to modify your XAML:
<DataGrid x:Name="dgInvDetails" ...> <!-- Define the shared MultiBinding as a resource --> <DataGrid.Resources> <MultiBinding x:Key="LoadDetailCommandParams" Converter="{StaticResource Converter}"> <Binding ElementName="dgInvDetails" Path="SelectedItem"/> <Binding ElementName="dgInvDetails" Path="CurrentColumn"/> </MultiBinding> </DataGrid.Resources> <DataGrid.InputBindings> <!-- Existing Left Double Click Trigger --> <MouseBinding Gesture="LeftDoubleClick" Command="{Binding LoadDetailGridCommand}" CommandParameter="{StaticResource LoadDetailCommandParams}"/> <!-- New Enter Key Trigger --> <KeyBinding Key="Enter" Command="{Binding LoadDetailGridCommand}" CommandParameter="{StaticResource LoadDetailCommandParams}"/> </DataGrid.InputBindings> <!-- Rest of your DataGrid content --> </DataGrid>
Why This Works
- Both triggers (
LeftDoubleClickandEnter) reference the same command (LoadDetailGridCommand) and the same parameter binding. - Your view model doesn’t need any changes—
LoadDetailGridCommandwill receive the exact same input (selected item + current column) from both actions. - By using a resource, you avoid duplicating the MultiBinding logic, making your XAML easier to maintain.
Quick Alternative (Without a Resource)
If you prefer not to add a resource, you can copy the MultiBinding directly into the KeyBinding. While this works, it duplicates code which is less ideal for long-term maintenance:
<DataGrid.InputBindings> <MouseBinding Gesture="LeftDoubleClick" Command="{Binding LoadDetailGridCommand}"> <MouseBinding.CommandParameter> <MultiBinding Converter="{StaticResource Converter}"> <Binding ElementName="dgInvDetails" Path="SelectedItem"/> <Binding ElementName="dgInvDetails" Path="CurrentColumn"/> </MultiBinding> </MouseBinding.CommandParameter> </MouseBinding> <KeyBinding Key="Enter" Command="{Binding LoadDetailGridCommand}"> <KeyBinding.CommandParameter> <MultiBinding Converter="{StaticResource Converter}"> <Binding ElementName="dgInvDetails" Path="SelectedItem"/> <Binding ElementName="dgInvDetails" Path="CurrentColumn"/> </MultiBinding> </KeyBinding.CommandParameter> </KeyBinding> </DataGrid.InputBindings>
I strongly recommend the first approach (using a resource) for better maintainability.
内容的提问来源于stack exchange,提问作者Keerthivel

