Dienstag, 11. Juni 2013

Changing the Image Source property with a trigger

To change the Source of an Image within a Trigger, the Source has to be set in a Style with the help of a Setter. This code won't work because the Trigger can't change/override a Property that has been set outside of the Style.
<Image Source="..\..\Images\OK.png">
    <Image.Style>
        <Style TargetType="{x:Type Image}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding HasError}" Value="True" >
                    <Setter Property="Source" Value="..\..\Images\Error.png"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>
Remove the Source attribute from the Image tag at the top and add it as a Setter in the Style. This will override whatever is applied by the style. You can move it to another DataTrigger or you can put it in a normal setter like so.
<Image>
    <Image.Style>
        <Style TargetType="{x:Type Image}">
            <Setter Property="Source" Value="..\..\Images\OK.png" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding HasError}" Value="True" >
                    <Setter Property="Source" Value="..\..\Images\Error.png"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>
This approach can also be used on a TextBlock if the text has to be changed with a Trigger.