Search code examples
wpfimagexamlmargindatatrigger

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:

  • Image doesn't seem to have a Style (actually it does, ignore this part)
  • I don't know how to test for "string is not empty".

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?


Solution

  • 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>