Reputation: 25927
I want to make a style for WPF treeview with the following rules:
I've extracted TreeView
's and TreeItem
's default style and made some modifications. Currently, skeleton of my code looks like the following:
<Window.Resources>
<Style TargetType="{x:Type TreeView}">
<Style.Resources>
<Style TargetType="{x:Type TreeViewItem}">
...
</Style>
</Style.Resources>
</Style>
</Window.Resources>
<Grid>
<TreeView>
<TreeViewItem Header="Root">
<TreeViewItem header="Inner" />
</TreeViewItem>
</TreeView>
</Grid>
I've customized look of the expand button, to check, if everything's OK. The code presented above works as planned.
But then I want to customize the look of the TreeViewItem
s outside the style. I write:
<TreeView>
<TreeView.Resources>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="HeaderTemplate">
<Setter.Value>
...
</Setter.Value>
</Setter>
</Style>
</TreeView.Resources>
<TreeViewItem Header="Root">
<TreeViewItem Header="Sub" />
</TreeViewItem>
</TreeView>
The items are styled as I want, but the expander button returns to its default look.
How can I achieve a styling mechanism I want?
You can download the whole sample source.
Upvotes: 2
Views: 3338
Reputation: 69959
If I understand you correctly, you want to make a Style
that is based on your default Style
. If that is correct, then you can use the Style.BasedOn
property if you provide your default Style
with an x:Key
value:
<Window.Resources>
<Style x:Key="DefaultTreeViewStyle" TargetType="{x:Type TreeView}">
<Style.Resources>
<Style TargetType="{x:Type TreeViewItem}">
...
</Style>
</Style.Resources>
</Style>
</Window.Resources>
Then you can base your overriding Style
on the default one like this:
<TreeView.Resources>
<Style TargetType="{x:Type TreeViewItem}"
BasedOn="{StaticResource DefaultTreeViewStyle}">
<Setter Property="HeaderTemplate">
<Setter.Value>
...
</Setter.Value>
</Setter>
</Style>
</TreeView.Resources>
The new Style
will have all of the settings from the default Style
plus any additional settings that you provide here.
Actually, thinking about it a bit more, I think that you can base your overriding Style
on the default one without setting the x:Key
value on the default one like this:
<TreeView.Resources>
<Style TargetType="{x:Type TreeViewItem}"
BasedOn="{StaticResource {x:Type TreeViewItem}}">
<Setter Property="HeaderTemplate">
<Setter.Value>
...
</Setter.Value>
</Setter>
</Style>
</TreeView.Resources>
Upvotes: 3