Skip to main content
 首页 » 编程设计

c#之使用带有 XAML 绑定(bind)的 StringFormat 将文件夹注入(inject)图像路径

2024年02月23日15jirigala

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

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

<Image x:Name  = "img"  
       Stretch = "None"  
       Source  = "{Binding StringFormat=Images\Icons\{0}\Multi.png,  
                   RelativeSource={RelativeSource Self},  
                   Path=Parent.Parent.Tag}" /> 

现在,我只是将文件夹名称存储在祖 parent 的标签中(将来我会绑定(bind)到其他东西,但现在我只是想把这些拼凑起来)。当我尝试构建上述 xaml 时,出现错误:

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

这让我相信它将 {0} 视为标记扩展,而不是我的字符串格式的一部分。我读过有关使用 {} 转义并使用单引号指定字符串格式的信息,但都不起作用:

Source  = "{Binding StringFormat={}Images\Icons\{0}\Multi.png, ... 

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

Source  = "{Binding StringFormat='Images\Icons\{0}\Multi.png', ... 
 
Source  = "{Binding StringFormat='{}Images\Icons\{0}\Multi.png', ... 

上面两个防止了错误的发生,但是导致图片源为null。

有人知道如何实现吗?

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

请您参考如下方法:

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

您可以通过向绑定(bind)添加一个转换器来解决此问题,该转换器采用格式字符串和您的标记、应用格式并将其转换为 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" /> 

并将您的源绑定(bind)修改为:

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