简体   繁体   中英

C# WPF Same Command for Multiple events

I have a WPF application in C# that follows MVVM pattern. I have a written the following code in xaml for double click event in a datagrid that will invoke a command.

<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>
</DataGrid.InputBindings>

I want the same to be triggered when enter key is pressed. Do I have to use the same code with KeyBinding and set Enter key for the same command or is there any better way of doing this?

Thanks in Advance!

You need to specify key binding for enter key.

Try below

<DataGrid>
  <DataGrid.InputBindings>
    <KeyBinding Command="{Binding LoadDetailGridCommand}" Key="Enter" >
<KeyBinding.CommandParameter>
            <MultiBinding Converter="{StaticResource Converter}">
                <Binding ElementName="dgInvDetails" Path="SelectedItem"/>
                <Binding ElementName="dgInvDetails" Path="CurrentColumn"/>
            </MultiBinding>
        </KeyBinding.CommandParameter>
</KeyBinding>
  </DataGrid.InputBindings>
</DataGrid>

If you want to reuse the binding, you could define it as a resource:

<Window.Resources>
    <local:MultiConverter x:Key="Converter" />
    <MultiBinding x:Key="binding" Converter="{StaticResource Converter}">
        <Binding ElementName="dgInvDetails" Path="SelectedItem"/>
        <Binding ElementName="dgInvDetails" Path="CurrentColumn"/>
    </MultiBinding>
</Window.Resources>

...and then use a custom markup extension to reference it:

<DataGrid.InputBindings>
    <KeyBinding Key="Return" Command="{Binding LoadDetailGridCommand}"
                CommandParameter="{local:BindingResourceExtension binding}" />
    <MouseBinding Gesture="LeftDoubleClick" Command="{Binding LoadDetailGridCommand}"
                  CommandParameter="{local:BindingResourceExtension binding}" />
</DataGrid.InputBindings>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM