Mike Spike
Mike Spike

Reputation: 499

wpf image source depending on object property

I have a boolean property in my class, say:

private bool isFolder;
public bool IsFolder{ get; set; }

and I have an image in xaml:

<Image Source="..">

I would like that image to have one imageSource when the IsFolder is true and another one - when it's false. How can I do that?

Thanks in advance.

Upvotes: 3

Views: 1634

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81253

DataTriggers are used for that purpose only.

Set default value in case IsFolder is false (bind it to NotFolderImage property). In case IsFolder value is set to true, set the source to other value (FolderImage in this case).

<Image>
    <Image.Style>
        <Style TargetType="Image">
            <Setter Property="Source" Value="{Binding NotFolderImage}"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsFolder}" Value="True">
                    <Setter Property="Source" Value="{Binding FolderImage}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>

Also, make sure underlying ViewModel class is implementing INotifyPropertyChanged event so that change in IsFolder property is propagated to UI.

Upvotes: 9

Related Questions