我创建了一个自定义控件库项目并执行了以下操作:
- 自定义控件来源于ComboBox
- 在Themes文件夹下添加资源字典文件 rd.xaml
在 rd.xaml 文件中定义一些样式
<Style x:Key="GroupComboBoxStyle" TargetType="{x:Type local:GroupComboBox}"> <Setter Property="ItemContainerStyle" > <Setter.Value> <Style TargetType="{x:Type ComboBoxItem}"> <Setter Property="IsEnabled" Value="{Binding Available}"/> </Style> </Setter.Value> </Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:GroupComboBox}"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> </Border> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="ItemsPanel"> <Setter.Value> <ItemsPanelTemplate> <WrapPanel IsItemsHost="True" Orientation="Horizontal" Width="150" Height="Auto" > <!-- add scroll bar --> </WrapPanel> </ItemsPanelTemplate> </Setter.Value> </Setter> <Setter Property="ItemTemplate"> <Setter.Value> <DataTemplate> <TextBlock Text="{Binding Item}" Width="40"/> </DataTemplate> </Setter.Value> </Setter> </Style> <CollectionViewSource x:Key="groupedData" Source="{Binding Items}"> <CollectionViewSource.GroupDescriptions> <PropertyGroupDescription PropertyName="Category"/> </CollectionViewSource.GroupDescriptions> </CollectionViewSource> <Style x:Key="groupComboBoxItemStyle" TargetType="{x:Type ComboBoxItem}"> <Setter Property="Width" Value="50" /> </Style> <GroupStyle x:Key="groupStyle"> <GroupStyle.HeaderTemplate> <DataTemplate> <Border BorderBrush="Black" BorderThickness="2"> <TextBlock Text="{Binding Name}" HorizontalAlignment="Stretch" Background="YellowGreen"/> </Border> </DataTemplate> </GroupStyle.HeaderTemplate> </GroupStyle>
然后我想在运行时将组样式设置为我的自定义控件
但是找不到groupstyle,如何从资源字典文件中获取呢?
public GroupComboBox()
{
GroupStyle style = new GroupStyle();
// get the groupstyle
style.HeaderTemplate = (DataTemplate)this.FindResource("groupStyle");
this.GroupStyle.Add(style);
}