我想設置控件的默認樣式,使用在控件中定義的資源字典,所以我可以添加事件處理程序到整個應用程序的樣式來改變基於綁定的背景顏色。當前向樣式添加事件處理程序時(在底部代碼片段中看到),該樣式將被覆蓋。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