Macho Gwapito
Macho Gwapito

Reputation: 149

WPF - ComboBox with Button items

I have this combobox and I wanted to add buttons as items in it. However, when I select the button from the combobox and click on the button, the action is not executed. The combobox's list falls instead. How should do this? If this is not possible, I think I'll just have to improvise. Suggestion will be appreciated. Thank you!

<ComboBox>
  <ComboBoxItem Name="Item1">
    <Button Name="Button1" Click="Button1_OnClick">first button</Button>
  </ComboBoxItem>
  <ComboBoxItem Name="Item2">
    <Button Name="Button2" Click="Button2_OnClick">second button</Button>
  </ComboBoxItem>
</ComboBox>

Upvotes: 4

Views: 10067

Answers (1)

Thanos Markou
Thanos Markou

Reputation: 2623

You need ItemTemplate, like this:

<ComboBox x:Name="CB" Width="150" ItemsSource="{BindingItems}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Button Content="Click" Click="Button_Click" /> 
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

And you need the event handler:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Do something
}

Upvotes: 8

Related Questions