Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to do this <Image Source="../Images/{Binding Path=Id}.jpg"/>?

I have an Employee ID and an image associated with that employee in as a resource in the project (the image is being shown in a list next to employees name).

So I think something like this

<DataTemplate DataType="{x:Type m:Employee}">
        <Grid>
            <Image Grid.Column="0" Name="image" Source="../Images/{Binding Path=Id}.jpg"/>

It's not valid XAML.

I suppose I could handle some databinding event in the codebehind and create the path there? Doesn't seem ideal to me.

I could store the path in my Employee class but that's terrible.

like image 474
Jim W says reinstate Monica Avatar asked Mar 22 '13 22:03

Jim W says reinstate Monica


1 Answers

You will have to use a IValueConverter

Heres a simple example passing in a String.Format as the converter paramerter

public class StringFormatToImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter is string)
        {
            return string.Format(parameter.ToString(), value);
        }
        return null;
    }

    public object ConvertBack(object value, Type targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}

Usage:

<XXXX.Resources>
    <local:StringFormatToImageSourceConverter x:Key="StringToImage" />
</XXXX.Resources>

<Image Source="{Binding Path=Id, Converter={StaticResource StringToImage}
     , ConverterParameter=../Images/{0}.jpg}" />

There is a way to keep it all in Xaml by using an invisible TextBlock to format the string, but not the best practice.

<Grid>
    <TextBlock x:Name="StringToImage" Visibility="Hidden" Text="{Binding Id, StringFormat=../Images/{0}.jpg}" />
    <Image Source="{Binding Text, ElementName=StringToImage}"/>
</Grid>
like image 112
sa_ddam213 Avatar answered Sep 21 '22 12:09

sa_ddam213