将字符串格式与 XAML 绑定结合使用,将文件夹注入图像路径



我正在尝试根据某些条件允许多个图标大小。为此,我有一堆文件夹:"图像\图标\...\*.png",其中...是大小(16、32、64、128、256 等)每个文件夹都包含针对给定大小优化的所有图标。

的问题我似乎无法在图像源路径中指定文件夹...即:

<Image x:Name  = "img" 
       Stretch = "None" 
       Source  = "{Binding StringFormat=ImagesIcons{0}Multi.png, 
                   RelativeSource={RelativeSource Self}, 
                   Path=Parent.Parent.Tag}" />
目前,我只是将

文件夹名称存储在祖父母的标签中(我将在未来绑定到其他内容,但现在我只是试图将这一点拼凑在一起)。当我尝试构建上述 xaml 时,出现错误:

The text Multi.png ... is not allowed after the closing } of a markup extension.

这导致我感到它将{0}视为标记扩展,而不是它是我的字符串格式的一部分。我已经阅读了有关使用 {} 转义并使用单引号指定字符串格式的信息,但两者都不起作用:

Source  = "{Binding StringFormat={}ImagesIcons{0}Multi.png, ...

上面返回的错误与我根本不转义时相同。.

Source  = "{Binding StringFormat='ImagesIcons{0}Multi.png', ...
Source  = "{Binding StringFormat='{}ImagesIcons{0}Multi.png', ...

上述两个可防止错误发生,但会导致图像源为空。

有谁知道如何实现这一目标?

(澄清一下,如果祖父母的标签设置为"16",那么我希望图像源绑定到图像\图标\16\多.png...如果标签设置为"32",那么我需要将源绑定到图像\图标\32\多.png。作为测试,我将祖父母标签设置为完整路径,并排除了字符串格式。与祖父母标记的相对绑定成功,并显示图像。仅当我尝试仅使用字符串格式指定文件夹名称以指定路径的其余部分时,它才会失败)。

Binding 的 StringFormatter 属性仅在目标类型为 String 时才有效。否则,它将被忽略。

可以通过向绑定添加转换器来解决此问题,该转换器采用格式字符串和标记,应用格式,并将其转换为 ImageSource。在 C# 中,转换器将如下所示:

public sealed class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
                          object parameter, CultureInfo culture)
    {
        if (parameter == null || parameter.Equals(String.Empty)) parameter = "{0}";
        string path = String.Format((string) parameter, value);
        return new BitmapImage(new Uri(path));
    }
    public object ConvertBack(object value, Type targetType,
                              object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

获得转换器后,可以将以下内容添加到 XAML 中的资源:

<local:ImageConverter x:Key="ImageConverter" />

并将源绑定修改为:

<Image x:Name="img"
       Stretch="None"
       Source="{Binding Parent.Parent.Tag, Converter={StaticResource ImageConverter}, 
                        ConverterParameter='Images\Icons\{0}\Multi.png', 
                        RelativeSource ={RelativeSource Mode=Self}}" 
/>

最新更新