WPF - Combo Box with Items that include a Button

2019-08-23 01:22发布

I have a ComboBox control in a window. I am reading the items that comprise the ComboBox at runtime from an XML file. What I would like to do is to include a Button object with each item so that if the user clicks the button, I can take appropriate action based on the item associated with the button. It might look something like this when the user drops down the list:

Item 1         [Button]
Another Item   [Button]
Item 3         [Button]

I don't have enough experience with WPF to know if this is possible, but a co-worker said it should be doable. Has anyone done this, or know how it might be done? Keep in mind the ComboBox control is created via XAML but the items are created at runtime.

1条回答
霸刀☆藐视天下
2楼-- · 2019-08-23 02:06

Here is one way:

<ComboBox x:Name="MyComboBox" VerticalAlignment="Top" HorizontalAlignment="Left">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>

                        <Label Content="{Binding}" Width="100" />
                        <Button Grid.Column="1">Do Something</Button>
                    </Grid>

                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

And in the code behind, I used a simple list of strings:

List<String> strings = new List<string>();

strings.Add("Item 1");
strings.Add("Another Item");
strings.Add("Item 3");

MyComboBox.ItemsSource = strings;

And this is what it looked like:

enter image description here

EDIT: Here is a resource on how to add a grid to a ComboBox drop down (this goes beyond the scope of an SO answer):

http://www.eggheadcafe.com/tutorials/aspnet/e8585e81-34c8-4808-ae3e-b8b35d738842/wpf-datagrid-as-combobox.aspx

查看更多
登录 后发表回答