首页 > 解决方案 > 使用环境变量作为图像的源路径

问题描述

我想在我的 wpf 应用程序中显示一个图像,并从环境变量中引用它的相对源。

我试过' {%test%}'

<Image Source="{%test%}\SD.png" Width="24" Height="24" Margin="2" />

我预计环境变量的正常使用会像 (test="C:\pics")<Image Source="C:\pics\SD.png" Width="24" Height="24" Margin="2" />一样展开,但它在编译时显示错误:

%test%Windows Presentation Foundation (WPF) 项目不支持“ ”错误。

标签: c#wpfxamlbindingenvironment-variables

解决方案


创建一个转换器,将文件名和环境变量转换为路径:

public class EnvironmentVariableConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Path.Combine(Environment.GetEnvironmentVariable((string)parameter), (string)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

您应该检查环境变量是否存在以及对象参数是否为字符串。为简洁起见,我跳过了这些检查。

这是 XAML:

<Window.Resources>
    <l:EnvironmentVariableConverter x:Key="EnvironmentVariableConverter" />
    <s:String x:Key="SD">SD.png</s:String>
</Window.Resources>

<Grid>
    <Image Source="{Binding Source={StaticResource SD},
        Converter={StaticResource EnvironmentVariableConverter},
        ConverterParameter=test}"
        />
</Grid>

“SD.png”现在是一种资源,因此您可以绑定到它而无需单独的视图模型。传递环境变量的ConverterParameter名称。


推荐阅读