WPF RotateTransform DataTrigger

PhilBrown picture PhilBrown · May 3, 2012 · Viewed 8.5k times · Source

Is it possible to use a DataTrigger to set the angle of a RotateTransform in WPF? If so, how?

Answer

Fredrik Hedblad picture Fredrik Hedblad · May 3, 2012

Sure, something like this should work

<TextBox>
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text}"
                             Value="RotateMe">
                    <Setter Property="LayoutTransform">
                        <Setter.Value>
                            <RotateTransform Angle="45"/>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>

Alternatively, if you already have a LayoutTransform set, you could use EnterActions and ExitActions of the DataTrigger

<TextBox>
    <TextBox.LayoutTransform>
        <RotateTransform Angle="0"/>
    </TextBox.LayoutTransform>
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text}"
                                Value="RotateMe">
                    <DataTrigger.EnterActions>
                        <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation Duration="0:0:0"
                                                 To="45"
                                                 Storyboard.TargetProperty="(LayoutTransform).(RotateTransform.Angle)"/>
                            </Storyboard>
                        </BeginStoryboard>
                    </DataTrigger.EnterActions>
                    <DataTrigger.ExitActions>
                        <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation Duration="0:0:0"
                                                 To="0"
                                                 Storyboard.TargetProperty="(LayoutTransform).(RotateTransform.Angle)"/>
                            </Storyboard>
                        </BeginStoryboard>
                    </DataTrigger.ExitActions>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>