Search code examples
wpfmvvmcontroltemplate

ComboBoxItem keyboard arrow & Enter press not working


I have a 'mvvm' based wpf application with a combobox style control Template like so,

<Style x:Key="Itmstyle" TargetType="ComboBoxItem">
<Setter Property="Template">
  <Setter.Value>
    <ControlTemplate TargetType="ComboBoxItem">
      <Button Content="{Binding Txt}" Command="{Binding DataContext.ClickCmd, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ComboBox}}}"
              Background="Transparent" BorderBrush="Transparent">          
        <Button.InputBindings>
          <KeyBinding Key="Enter" Command="{Binding DataContext.ClickCmd, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ComboBox}}}"/>
        </Button.InputBindings>
      </Button>
    </ControlTemplate>
  </Setter.Value>
</Setter>

Style is used like this,

<ComboBox ItemContainerStyle="{StaticResource Itmstyle}"
      ItemsSource="{Binding Values}"
      DisplayMemberPath="Name"
      SelectedIndex="{Binding Indx}"
      IsSynchronizedWithCurrentItem="True"/>

When i use the keyboard arrow the buttons (in the style) do not get highlighted, only the dotted focus around the item appears; and when i press Enter key the ClickCmd is not executing.. Any idea! please let me know. Thanks a lot.


Solution

  • If you want a combo selection to both change selection AND fire a command, I'd say the easiest way would be to add a Button as you have done, but process the Click event in code behind to set the combo:

    eg

    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding Txt}" 
                    Background="Transparent" BorderBrush="Transparent"
                    Command="{Binding DataContext.ClickCmd, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ComboBox}}}"
                    Click="ComboItem_Click"/>
            </Button>
        </DataTemplate>
    </ComboBox.ItemTemplate>
    

    Then in code behind:

    private void ComboItem_Click(object sender, RoutedEventArgs e)
    {
        _combo.SelectedItem = ((Button)e.Source).DataContext;
    }