Warm tip: This article is reproduced from stackoverflow.com, please click
converters wpf binding conditional boolean-expression

Bind Image.Source according to Boolean without a converter?

发布于 2020-04-05 00:27:46

I want to have an image bound to a boolean and have the source of the image to depend on the boolean value

i.e. true source="image1" false source="image2"

I was wondering if there is a way to do it inline without need for a converter.

Questioner
Shimmy
Viewed
63
Grokys 2009-11-03 23:33

You can create a style on the Image which uses a DataTrigger to swap the image source depending on a binding. In this example the image changes depending on the value of a boolean called simply "Value".

    <Image Width="16">
        <Image.Style>
            <Style TargetType="{x:Type Image}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Value}" Value="False">
                        <Setter Property="Source" Value="Resources/image1.png"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Value}" Value="True">
                        <Setter Property="Source" Value="Resources/image2.png"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Image.Style>
    </Image>