定義在資源DataTemple
地方。並將其用於您需要的每個Combobox
。
下面是代碼:
<Grid>
<Grid.Resources>
<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>
</Grid.Resources>
<ComboBox Height="27" Width="195" DisplayMemberPath="Item" Name="cboGroup"
ItemContainerStyle="{StaticResource comboBoxItemStyle}">
<ComboBox.GroupStyle>
<GroupStyle HeaderTemplate="{StaticResource groupStyle}"/>
</ComboBox.GroupStyle>
</ComboBox>
</Grid>
編輯:我創建了一個新的組合框,並設置一些項目,並設置你正在尋找的風格。 (我更新了你鏈接中的代碼)
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
ComboBox comboBox1 = new ComboBox();
comboBox1.Height = 23;
comboBox1.Width = 200;
GroupStyle style = new GroupStyle();
style.HeaderTemplate = (DataTemplate)this.FindResource("groupStyle");
comboBox1.GroupStyle.Add(style);
comboBox1.DisplayMemberPath = "Item";
ObservableCollection<CategoryItem<string>> items = new ObservableCollection<CategoryItem<string>>();
items.Add(new CategoryItem<string> { Category = "Warm Colors", Item = "Orange" });
items.Add(new CategoryItem<string> { Category = "Warm Colors", Item = "Red" });
items.Add(new CategoryItem<string> { Category = "Warm Colors", Item = "Pink" });
items.Add(new CategoryItem<string> { Category = "Cool Colors", Item = "Blue" });
items.Add(new CategoryItem<string> { Category = "Cool Colors", Item = "Purple" });
items.Add(new CategoryItem<string> { Category = "Cool Colors", Item = "Green" });
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);
myGrid.Children.Add(comboBox1);
}
}
public class CategoryItem<T>
{
public T Item { get; set; }
public string Category { get; set; }
}
感謝您的建議 - 我怎麼能運用它爲每一個組合框,我需要?你能否展示一些示例C#代碼? – 2013-03-24 12:48:53
對於您應該通過'StaticResource'結合設置它'GroupStyle'的'HeaderTemplate'財產每組合框。我要編輯我的代碼... – 2013-03-24 12:51:06
這可以通過後面的代碼應用,或只有XAML?正如我試圖通過代碼背後所做的那樣。謝謝 – 2013-03-24 12:52:05