Conditional structure of Elements based on DataContext

In my MV-VM application, I have to show the user avatar. The image is provided in a property of type ImageSource for the ViewModel. So what I have at present:

<Image Source="{Binding Path=UserAvatar}"/>

However, some users may not configure the avatar, so UserAvatar matters null. In this case, I want to show the default avatar. No one but the view should know about the default image because it is just a view problem.

So, how can I show an image with a given ImageSource or a specific resource, if ImageSource null. Should I use some kind of DataTemplate with DataTriggers? Since then, I have only used them for ItemsControls, so I don’t know.

+3
source share
1 answer

You guessed it right, templates and triggers are really your friend here.

Here is an implementation using ContentControl:

<ContentControl Content="{Binding Path=UserAvatar}">
    <ContentControl.ContentTemplate>
        <DataTemplate>
            <Image x:Name="image" Source="{Binding}"/>
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding}" Value="{x:Null}">
                    <Setter TargetName="image" Property="Source" Value="--your awesome default image here--" />
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

And in a situation where your default value is not equal ImageSource, and you want to play a little with other controls, you can always resort to the property Visibilty:

<ContentControl Content="{Binding Path=UserAvatar}">
    <ContentControl.ContentTemplate>
        <DataTemplate>
            <Grid>
                <Image x:Name="image" Source="{Binding}" />
                <Canvas x:Name="defaultImage" Visibility="Collapsed" />
            </Grid>
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding}" Value="{x:Null}">
                    <Setter TargetName="image" Property="Visibility" Value="Collapsed" />
                    <Setter TargetName="defaultImage" Property="Visibility" Value="Visible" />
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

Hope this helps.

+6
source

Source: https://habr.com/ru/post/1713944/


All Articles