Tuesday, 13 August 2013

WPF BasedOn Style with Style.Resources

WPF BasedOn Style with Style.Resources

I'm asking for your help, as I can't get my 'BasedOn' style to work
properly. Here is the situation :
I have my base style defined in a ResourceDictionary, like this :
Styles.xaml
<Style TargetType="{x:Type TreeView}" x:Key="MyBaseStyle">
<Style.Resources>
<HierarchicalDataTemplate ...>
...
</HierarchicalDataTemplate>
<DataTemplate ...>
...
</DataTemplate>
<Style TargetType="{x:Type TreeViewItem}">
...
</Style>
</Style.Resources>
<!-- This is for test purpose -->
<Setter Property="Background" Value="Red" />
I merge this dictionary in my App.xaml like this :
App.xaml
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Here is what I've done before, that worked perfectly, in my main window :
MainWindow.xaml
<TreeView ... Style="{StaticResource MyBaseStyle}" />
But because I have multiple TreeViews in my application, I need to apply
MyBaseStyle to them, and add a DataTrigger different for each TreeView. I
tried this :
MainWindow.xaml
<TreeView ...>
<TreeView.Style>
<Style TargetType="{x:Type TreeView}" BasedOn="{StaticResource
MyBaseStyle}">
<Style.Triggers>
<!-- DataTrigger here -->
</Style.Triggers>
</Style>
</TreeView.Style>
</TreeView>
The problem is that the HierarchicalDataTemplate in MyBaseStyle is not
working. The Red background of MyBaseStyle appears, and the DataTrigger
works fine, but not the template. It seems like the program is ignoring
the Style.Resources of the BasedOn style ??
I think it could be a style scope problem, but how can I solve it, without
having to repeat code for every TreeView ? Someone has already been in
this situation, and know the cause of the problem ?
Thank you for your help, Arnaud.

No comments:

Post a Comment