What's the correct way to do this ?

后端 未结 1 1839
南旧
南旧 2021-01-03 04:17

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 th

相关标签:
1条回答
  • 2021-01-03 04:38

    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>
    
    0 讨论(0)
提交回复
热议问题