2013-03-24 73 views
0

我試圖將標籤存儲在ComboBox中,並帶有類別 - 類似this顯示控件時出現問題

但是,組合框項目出現,像這樣:

enter image description here

這是我迄今所做的:

的App.xaml

<DataTemplate x:Key="groupStyle"> 
    <Label FontWeight="Bold" Content="{Binding Name}"/> 
</DataTemplate> 

代碼背後

ComboBox comboBox1 = new ComboBox(); 

    GroupStyle style = new GroupStyle(); 
    style.HeaderTemplate = (DataTemplate)this.FindResource("groupStyle"); 
    comboBox1.GroupStyle.Add(style); 
    comboBox1.DisplayMemberPath = "Item"; 
    ObservableCollection<CategoryItem<Label>> items = new ObservableCollection<CategoryItem<string>>(); 

    Label label = new Label(); 
    TextBlock block = new TextBlock(); 
    block.Text = "Text"; 
    label.Content = block; 

    items.Add(new CategoryItem<Label> { Category = "Category", Item = label }); 

    CollectionViewSource cvs = new CollectionViewSource(); 
    cvs.GroupDescriptions.Add(new PropertyGroupDescription("Category")); 
    cvs.Source = items; 

    Binding b = new Binding(); 
    b.Source = cvs; 
    BindingOperations.SetBinding(comboBox1, ComboBox.ItemsSourceProperty, b); 

public class CategoryItem<T> 
{ 
    public T Item { get; set; } 
    public string Category { get; 
} 

回答

2

您應該使用ItemContainerStyle。然而,你可能有App.xaml中看看this

<DataTemplate x:Key="groupStyle"> 
    <TextBlock FontWeight="Bold" Text="{Binding Name}"/> 
</DataTemplate> 
<Style TargetType="{x:Type ComboBoxItem}" x:Key="comboBoxItemStyle"> 
    <Setter Property="Template" > 
     <Setter.Value> 
      <ControlTemplate> 
       <Label Background="Red" Content="{Binding Item}"/> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

後面的代碼:

ComboBox comboBox1 = new ComboBox(); 

GroupStyle style = new GroupStyle(); 
style.HeaderTemplate = (DataTemplate)this.FindResource("groupStyle"); 
comboBox1.GroupStyle.Add(style); 
comboBox1.DisplayMemberPath = "Item"; 

// Here is what you are looking for 
comboBox1.ItemContainerStyle = (Style)this.FindResource("comboBoxItemStyle"); 


ObservableCollection<CategoryItem<string>> items = new ObservableCollection<CategoryItem<string>>(); 

CollectionViewSource cvs = new CollectionViewSource(); 
cvs.GroupDescriptions.Add(new PropertyGroupDescription("Category")); 
cvs.Source = items; 

Binding b = new Binding(); 
b.Source = cvs; 
BindingOperations.SetBinding(
      comboBox1, ComboBox.ItemsSourceProperty, b); 
+0

太感謝你了,它的工作原理:) – 2013-03-24 14:31:16

+0

唯一的問題現在似乎當我將鼠標放在標籤上時,它們周圍沒有藍色邊框,就像懸停在ComboBoxItem – 2013-03-24 14:32:30

+0

上我想你應該定義一些在ControlTemplate中觸發,但在這種情況下我不夠好。我編輯了我的帖子,你可以從我提供的鏈接中獲得一些想法。 – 2013-03-24 14:41:14

相關問題