Drakestar
Drakestar

Reputation: 748

DataTriger Style Setter for Image Element

I have an image element that is populated via databinding - if the binding returns a path, the image is drawn. If not (path comes in an an empty string), we get no image.

<Image Source="{Binding Path=.Screenshot, Mode=OneWay}" Stretch="Fill"  Margin="5,5,5,5" />

That works well, except that the margin is applied to the layout no matter what (which looks bad for empty images). I figured I'd do a DataTrigger instead that only applies the margin is the path is not empty, but:

What I'd like to do is something like the pseudo-XAML below. Is that possible in XAML?

<Image Source="{Binding Path=.Screenshot, Mode=OneWay}" Stretch="Fill" >
<Image.Style>
    <Style TargetType="Image">
        <Setter Property="Margin" Value="0,0,0,0" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=.Screenshot}" Value="!NullOrEmpty">
                <Setter Property="Margin" Value="5,5,5,5" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Image.Style>

Should I be maybe using an entirely different approach for this?

Upvotes: 0

Views: 682

Answers (1)

Clemens
Clemens

Reputation: 128085

Do it the other way round, by having a DataTrigger for the values null and "":

<Style TargetType="Image">
    <Setter Property="Margin" Value="5,5,5,5" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=Screenshot}" Value="{x:Null}">
            <Setter Property="Margin" Value="0,0,0,0" />
        </DataTrigger>
        <DataTrigger Binding="{Binding Path=Screenshot}" Value="">
            <Setter Property="Margin" Value="0,0,0,0" />
        </DataTrigger>
    </Style.Triggers>
</Style>

You may probably also just have a Trigger on the Images's Source property:

<Style TargetType="Image">
    <Setter Property="Margin" Value="5,5,5,5" />
    <Style.Triggers>
        <Trigger Property="Source" Value="{x:Null}">
            <Setter Property="Margin" Value="0,0,0,0" />
        </Trigger>
    </Style.Triggers>
</Style>

Upvotes: 1

Related Questions