c# - 使用环境变量作为图像的源路径
问题描述
我想在我的 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) 项目不支持“ ”错误。
解决方案
创建一个转换器,将文件名和环境变量转换为路径:
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
名称。
推荐阅读
- reporting-services - 我们可以在 SSRS 报告中添加超链接到报告描述属性吗
- c# - 使用 MVC 代码显示无效登录详细信息消息
- java - 热点编译器不生成 aes-ni 指令
- python - PySpark 不会为 Parquet 格式的 TimeStamp 和 Decimal 列编写统计信息
- django - Django,CSRF 令牌出错!我在哪里看?
- php - 如何在没有任何固定名称的 url 中使用类别和子类别?
- oauth-2.0 - Discord Oauth2 收到“无效客户端”错误
- ads - 尝试将构建上传到商店时,tvOS 的代码签名“ClientSideInteractiveMediaAds.framework”失败
- r - Surv 错误消息“开始和停止的长度不同”实际上是什么意思?
- google-bigquery - Google Cloud Pub/Sub - Cloud Function & Bigquery - 数据插入未发生