Choose Style depending on property

2.5k views Asked by At

Is it possible to set the Style Property (of a Button for example) from within a DataTrigger on the same control?

I would like to define my Default-, MouseOver- and Selected-Styles as resources to reuse them later on. However handling MouseOver (and other) events seems to be usually done by setting the changed properties individually in a DataTrigger instead of assigning a new Style to the Control (which makes sense since the datatrigger would get removed by assigning another style).

1

There are 1 answers

0
Olaru Mircea On BEST ANSWER

You can accomplish something like this with DataTamplates:

<Window x:Class="StackSimpleSample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.Resources>
        <Style x:Key="RedStyle" TargetType="TextBlock">
            <Setter Property="Foreground" Value="Red"/>
        </Style>

        <Style x:Key="GreenStyle" TargetType="TextBlock">
            <Setter Property="Foreground" Value="Green"/>
        </Style>

        <DataTemplate x:Key="DefaultDataTemplate">
            <TextBlock Text="TestColor" Style="{StaticResource RedStyle}" HorizontalAlignment="Center"/>
        </DataTemplate>

        <DataTemplate x:Key="OnMouseOverDataTemplate">
            <TextBlock Text="TestColor" Style="{StaticResource GreenStyle}" HorizontalAlignment="Center"/>
        </DataTemplate>

        <Style x:Key="StyleDefault" TargetType="{x:Type ContentPresenter}">
            <Setter Property="ContentTemplate" Value="{DynamicResource DefaultDataTemplate}"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="ContentTemplate" Value="{DynamicResource OnMouseOverDataTemplate }"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Grid.Resources>
    <Grid>
        <ContentPresenter Style="{DynamicResource StyleDefault}" Content="{Binding}" />
    </Grid>
  </Grid>
</Window>

Give it a try. You are basically using a Style which will change two ContentTemplates according to the IsMouseOver event.