简体   繁体   中英

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> 

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
}

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