简体   繁体   English

Image.Source在使用字符串格式化绑定时不显示图像

[英]Image.Source not showing image when using a string formatted binding

I'm currently using the following code to build a ComboBox control with flag images and canadian province names. 我目前正在使用以下代码来构建带有标志图像和加拿大省名称的ComboBox控件。 However the images are not showing up in the control. 但是图像没有显示在控件中。 I have tested the binding and it generated the location properly, but the image just doesn't come up in the control. 我已经测试了绑定并且它正确地生成了位置,但是图像不会出现在控件中。

Not sure what is wrong here any help would be appreciated 不知道这里有什么问题,我们将不胜感激

Code: 码:

<ComboBox x:Name="cb_Provinces" Text="Province"SelectionChanged="ComboBox_SelectionChanged"  SelectedValuePath="ProvinceCode" ItemsSource="{Binding Provinces, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}">
    <ComboBox.ItemTemplate>
        <DataTemplate >
            <StackPanel>
                <StackPanel x:Name="stk_ComboTemplate" Orientation="Horizontal" HorizontalAlignment="Left">
                    <Image Width="25" Margin="10" Source="{Binding ProvinceCode, StringFormat=/CanadaTreeSvc.Interface;component/Resources/img/flags/\{0\}.gif}" />

                    <TextBlock Text="{Binding ProvinceName}"/>

                </StackPanel>
                <TextBlock FontSize="10" Foreground="Gray" Text="{Binding ProvinceCode, StringFormat=/CanadaTreeSvc.Interface;component/Resources/img/flags/\{0\}.gif}"/>

            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>

Resulting Output: 结果输出:

在此输入图像描述

StringFormat only works if the target is of type String . StringFormat仅在目标类型为String Because Image Source is of type Uri the StringFormat will never be used in the Binding 因为Image Source的类型为Uri所以StringFormat永远不会在Binding

The best option would be to make a IValueConverter to format the string and return it to the Image Source property. 最好的选择是使IValueConverter格式化string并将其返回到Image Source属性。

Example: 例:

public class ProvinceNameToImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return string.Format("/CanadaTreeSvc.Interface;component/Resources/img/flags/\{0\}.gif", value);
    }

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

Usage: 用法:

<Window.Resources>
    <local:ProvinceNameToImageSourceConverter x:Key="ImageConverter" />
</Window.Resources>

..................

   <Image Source="{Binding ProvinceCode, Converter={StaticResource ImageConverter}}" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM