Search code examples
c#wpfbindingdatatemplate

WPF DataTemplate specify an alternative source


I have a DataTemplate which is based on an XmlNode.

<DataTemplate DataType="person" >
    <Border Margin="30" CornerRadius="25">
        <Border.Background>
            <ImageBrush ImageSource="{Binding Path=[dog], Source={????}}" />
        </Border.Background>
        <TextBlock Text="{Binding XPath=@forename}" />
    </Border>
</DataTemplate>

I then have a ContentControl in my Window which has its Contentset to an XmlNode with an element name of 'person' and an attribute name of 'forename'.

This all works fine, but I now want to apply an alternative Source for the Border background image.

I have a class which 'feeds' the uri of an image, after ensuring that the image is available. This class is called ResourceLoader and it works perfectly in any control that's in my main window, but I can't work out how to refer to it from my DataTemplate.

The ResourceLoader is the main DataContext of the Window.

I hope this makes sense.

Thanks, Rich


Solution

  • Right, I think I've solved this.

    I've added a new item to my Resources

    <local:ResourceLoader x:Key="allimages" />
    

    Then, in my ImageBrush I'm specifying...

    <ImageBrush ImageSource="{Binding Source={StaticResource allimages}, Path=[dog]}" />
    

    Problem solved.