WPF - 带有包含按钮的项目的组合框 [英] WPF - Combo Box with Items that include a Button

查看:27
本文介绍了WPF - 带有包含按钮的项目的组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个窗口中有一个 ComboBox 控件.我正在从 XML 文件中读取运行时组成 ComboBox 的项目.我想要做的是在每个项目中包含一个 Button 对象,这样如果用户单击按钮,我就可以根据与按钮关联的项目采取适当的操作.当用户下拉列表时,它可能看起来像这样:

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]

我对 WPF 的经验不足,无法知道这是否可行,但一位同事说这应该可行.有没有人做过这个,或者知道怎么做?请记住,ComboBox 控件是通过 XAML 创建的,但项目是在运行时创建的.

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.

推荐答案

这是一种方法:

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

这就是它的样子:

这是关于如何将网格添加到 ComboBox 下拉列表的资源(这超出了 SO 答案的范围):

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

这篇关于WPF - 带有包含按钮的项目的组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆