Robert F.
Robert F.

Reputation: 465

How to "inject" style in a DataTemplate

I am trying to separate the DataTemplates from the Styles in my code. I use DataTemplate to define, e.g. that the data should be displayed as two buttons and I use styles to define, e.g. that the background of those buttons should be green.

What I am trying to achieve is having a DataTemplate defined in one file and using that in multiple UserControls where the style comes from the UserControls.

Let's say I have the following style in the Resources of a UserControl:

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Foreground" Value="Green"/>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Foreground" Value="Red"/>
        </Trigger>
    </Style.Triggers>
</Style>

Another UserControl might have something similar with different colors.

Then, I have a ContentControl in that UserControl that will have some view model and some DataTemplate:

<ContentControl Content="{Binding SelectedViewModel}"
                ContentTemplate="{Binding SelectedDataTemplate}"/> 

The DataTemplate can be something as simple as this:

<DataTemplate x:Key="TwoButtonsTemplate">
    <StackPanel>
        <Button Content="One"/>
        <Button Content="Two"/>
    </StackPanel>
</DataTemplate>

I would like the two buttons to have the ButtonStyle from the UserControl.Resources without directly referencing it. (So the DataTemplate can come from a different file or being able to use the DataTemplate in a similar context with another UserControl's style).

I tried to change the TargetType of ButtonStyle to ContentControl, assign the style to the ContentControl and set Foreground="{TemplatedParent Foreground}" on the Buttons, but in this way both Foreground will change when any of them (i.e. the ContentControl itself) is hovered.

Is there any way of "inheriting" a style in the DataTemplate or "injecting" the style from the UserControl?

P.S. I understand if I move the style into a separate file and reference that in the DataTemplate file I can simply use it as StaticResource, but that will couple the DataTemplate to that specific style and I won't be able to re-use it with other styles.

Upvotes: 0

Views: 170

Answers (1)

ASh
ASh

Reputation: 35646

try DynamicResource:

<DataTemplate x:Key="TwoButtonsTemplate">
    <StackPanel>
        <Button Content="One" Style="{DynamicResource ButtonStyle}"/>
        <Button Content="Two" Style="{DynamicResource ButtonStyle}"/>
    </StackPanel>
</DataTemplate>

when TwoButtonsTemplate template is instantiated in UserControl, which declares ButtonStyle resource, that resource will be found and applied to buttons.

Upvotes: 1

Related Questions