xerxos
xerxos

Reputation: 55

How to change Image source using a trigger/behavior?

I have the following XAML markup, using WinUi 1.6.5, .NET 9 and C# 13.

This my DataTemplate for usage in an ItemView:

<DataTemplate x:DataType="MyModel">
    ...
    <Image x:Name="Image1" Grid.Row="0" Grid.Column="1" Height="16" />
    <Image x:Name="Image2" Grid.Row="1" Grid.Column="1" Height="16" />
</DataTemplate>

In my model class, I have the following properties:

public string Type => ""; // Can be either Case1 or Case2
public string TypeImageUri => "/Assets/picture.png";

Now I would like to assign that TypeImageUri to one of that Image controls depending on the Type property, like this:

<Image x:Name="Image1" Grid.Row="0" Grid.Column="1" Height="16">
    <interactivity:Interaction.Behaviors>
        <interactivity:DataTriggerBehavior Binding="{Binding Type}" ComparisonCondition="Equal" Value="Case1">
            <interactivity:ChangePropertyAction TargetObject="{Binding ElementName=Image1}" PropertyName="Source" Value="{x:Bind TypeImageUri}" />
        </interactivity:DataTriggerBehavior>
    </interactivity:Interaction.Behaviors>
</Image>

Unfortunately, it's not working, it seems that's not the meaning of the matter of Behaviors. Is there some way to make this approach work? I don't want to have to do this in code.

Best regards

Upvotes: 0

Views: 73

Answers (1)

Andrew KeepCoding
Andrew KeepCoding

Reputation: 13666

I agree with the suggestion in the comments. This seems to be easier with a value converter. Or with a function maybe. (I have a video for this.)

I tried to reproduce your issue and created a test app based on your code but it worked. My first guess is that the image files are not set as Content.

enter image description here

Upvotes: 0

Related Questions