0

我正在尝试将标签存储在带有类别的 ComboBox 中 - 像这样

但是,ComboBox 项目看起来像这样:

在此处输入图像描述

这是我到目前为止所做的:

应用程序.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; 
}
4

1 回答 1

2

你应该使用ItemContainerStyle. 但是你可以看看这个

应用程序.Xaml

<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);
于 2013-03-24T14:27:02.613 回答