WPF 使用绑定分配静态资源 [英] WPF use binding to assign static resource
问题描述
我正在尝试使用枚举来显示相应的图像.为此,我有一个值转换器,可将枚举转换为正确的资源名称.我的资源定义如下:
I am trying to use an enum to display a corresponding image. For this I have a value converter that converts an enum to the correct resource name. My resources are defined as follows:
<UserControl.Resources>
<BitmapImage x:Key="AlarmCat1" UriSource="/Lib.Infrastructure;component/Resources/msg_cat1.bmp" />
<BitmapImage x:Key="AlarmCat2" UriSource="/Lib.Infrastructure;component/Resources/msg_cat2.bmp" />
<BitmapImage x:Key="AlarmCat3" UriSource="/Lib.Infrastructure;component/Resources/msg_cat3.bmp" />
<converters:JamCategoryToImageConverter x:Key="AlarmCategoryConverter" />
</UserControl.Resources>
这有效:
<Image Source="{StaticResource AlarmCat1}" />
但这不是,转换器被调用并传回正确的值.正确的语法是什么?
But this doesn't, the converter is called and the correct value is passed back. What is the correct syntax?
<Image Source="{StaticResource { Binding CurrentAlarmItem.AlarmCategory, Converter={StaticResource AlarmCategoryConverter}}}" />
为了完整起见,这是转换函数:
For completeness, this is the convert function:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
switch ((AlarmCategory)value)
{
case AlarmCategory.Category1:
return "AlarmCat1";
case AlarmCategory.Category2:
return "AlarmCat2";
case AlarmCategory.Category3:
return "AlarmCat3";
default:
return null;
}
}
推荐答案
我会返回转换器中的资源:
I would return the resource in the converter:
<Image Source="{Binding CurrentAlarmItem.AlarmCategory, Converter={StaticResource AlarmCategoryConverter}}" />
在您的转换器中执行以下操作:
In your converter do something like this:
return Application.Current.FindResource("AlarmCat1") as BitmapImage;
使用资源字典 (app.xaml) 为整个应用程序设置资源
Set your resources for the complete application with the use of resourcedictionary (app.xaml)
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
在你的字典中 (Dictionary1.xaml)
In your Dictionary (Dictionary1.xaml)
<BitmapImage x:Key="AlarmCat1" UriSource="bh.jpg" />
因为您的资源现在是在应用程序级别定义的,所以代码现在将找到您的资源并将其返回.
Because your resources are now defined on applicationlevel, the code will now find your resource and give it back.
这篇关于WPF 使用绑定分配静态资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!