我想设置控件的默认样式,使用在控件中定义的资源字典,所以我可以添加事件处理程序到整个应用程序的样式来改变基于绑定的背景颜色。当前向样式添加事件处理程序时(在底部代码片段中看到),该样式将被覆盖。XAML扩展列表框和ListBoxItem控件
我对控件的外观感到满意,所以我从样式中删除了代码,使其更具可读性。
问题是当向bubblelist
添加触发器时,默认样式在上一个代码片段中被覆盖。控制背后
代码:
public partial class BubbleList : ListBox
{
public BubbleList()
{
InitializeComponent();
}
static BubbleList()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(BubbleList),
new FrameworkPropertyMetadata(typeof(BubbleList)));
}
}
从这里找到:https://stackoverflow.com/a/28715964/3603938
的风格是如何设置的控制:
<ListBox ... >
<ListBox.Resources>
<Style TargetType="{x:Type local:BubbleList}"
BasedOn="{StaticResource {x:Type ListBox}}">
....
</Style>
</ListBox.Resources>
</ListBox>
期望usuage:
<lists:BubbleList ...>
<lists:BubbleList.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
...
</Style.Triggers>
</Style>
</lists:BubbleList.ItemContainerStyle>
<lists:BubbleList.ItemTemplate>
<DataTemplate>
<Label ... />
</DataTemplate>
</lists:BubbleList.ItemTemplate>
</lists:BubbleList>
完整的解决方案
基于克莱门斯的解决方案我选择使用的主题/ generic.xaml资源字典以包含控件的样式。
它覆盖默认ListBoxItem中与BubbleListItempublic class BubbleList : ListBox
{
static BubbleList()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(BubbleList),
new FrameworkPropertyMetadata(typeof(BubbleList)));
}
protected override bool IsItemItsOwnContainerOverride(object item)
{
return item is BubbleListItem;
}
protected override DependencyObject GetContainerForItemOverride()
{
return new BubbleListItem();
}
}
BubbleListItem具有依赖性
BubbleList类中删除
public class BubbleListItem : ListBoxItem
{
...
static BubbleListItem()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(BubbleListItem),
new FrameworkPropertyMetadata(typeof(BubbleListItem)));
}
...
}
的样式都在liststyles.xaml:
<ResourceDictionary ... >
<Style TargetType="{x:Type local:BubbleListItem}"
BasedOn="{StaticResource {x:Type ListBoxItem}}">
...
</Style>
<Style TargetType="{x:Type local:BubbleList}"
BasedOn="{StaticResource {x:Type ListBox}}">
...
</Style>
</ResourceDictionary>
主题/ generic.xaml
<ResourceDictionary ... >
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="liststyles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
用法:
<lists:BubbleList ... >
<lists:BubbleList.ItemContainerStyle>
<Style TargetType="{x:Type lists:BubbleListItem}"
BasedOn="{StaticResource {x:Type lists:BubbleListItem}}">
<Style.Triggers>
...
</Style.Triggers>
</Style>
</lists:BubbleList.ItemContainerStyle>
<lists:BubbleList.ItemTemplate>
<DataTemplate>
<Label ... />
</DataTemplate>
</lists:BubbleList.ItemTemplate>
</lists:BubbleList>
“我假设有一种方法来指定资源位于默认样式覆盖的位置。“我想不是,它应该在'Themes/Generic.xaml'中。 – Clemens