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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With