2011-01-31 38 views
0

我在窗口中有一個組合框控件。我正在從XML文件讀取在運行時組成ComboBox的項目。我想要做的是在每個項目中包含一個Button對象,這樣如果用戶單擊該按鈕,我可以根據與該按鈕關聯的項目採取適當的操作。WPF - 包含一個按鈕項目的組合框

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

我沒有與WPF足夠的經驗,知道這是可能的,但同事說,這應該是可行的:當用戶下拉列表中它可能是這個樣子。有沒有人做過這件事,或者知道如何做?請記住,ComboBox控件是通過XAML創建的,但是這些項目是在運行時創建的。

回答

6

這裏有一種方法:

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

而且在後面的代碼,我用一個簡單的字符串列表:

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

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

MyComboBox.ItemsSource = strings; 

而這正是它看起來像:

enter image description here

編輯:這裏是如何添加一個網格,組合框下拉資源(這超出了一個SO回答範圍):

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

+0

@RQDQ - 謝謝你。這個XAML代碼塊與我的主要.XAML文件相關? – 2011-01-31 21:04:12