0
votes

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.

1
You're replacing the entire ControlTemplate, so you're losing the built in highlighting. Just use a DataTemplate inside ComboBox.ItemTemplate instead. - GazTheDestroyer
@GazTheDestroyer: Thanks for the reply. I added the DataTemplate. But now if i click on the button the SelectedIndex is not updated in viewModel, and if i click on the combobox item (little outside of the button) the index is updated but the ClickCmd is not executed. - Joe
What do you want to happen? If you just want a click to select the combo item, why do you need a button in there? - GazTheDestroyer
I am trying to select (and execute ClickCmd) when the same entry is clicked in ComboBox dropdown, but the SelectionChanged doesn't fire again when selecting the same entry. To overcome this problem i tried to put the Button as a template for all the entries in my combobox. - Joe

1 Answers

1
votes

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;
}