我在ResourceDictionary中定义了一个位图图像,如下所示:
<BitmapImage x:Key="Skin_Image_Back" UriSource="./images/back.png" />
像那样加载资源字典
var dict = Application.LoadComponent(
new Uri("TestProject.DefaultStyle;component/Style.xaml",
UriKind.Relative)) as ResourceDictionary;
Application.Current.Resources.MergedDictionaries.Add(dict);
当我通过XAML和StaticResource标记扩展(如
<Image Source="{StaticResource Skin_Image_Back}" />
一切正常。
但当我想通过以下方式设置源图像时:
MyObject.ImageUrl = FindResource("Skin_Image_Back").ToString();
findresource返回一个uri,它将导致
"pack://application:,,,/TestProject.DefaultStyle;component/images/back.png"
通过一个转换器
<Image Source="{Binding ImageURL, Converter={StaticResource StringToImageThumbSourceConverter}}" />
执行为
<Converter:StringToImageThumbSource x:Key="StringToImageThumbSourceConverter" />
和
public class StringToImageThumbSource : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
try {
if(value != null) {
string s = value.ToString();
if(!string.IsNullOrEmpty(s) && File.Exists(s)) {
BitmapImage bi = new BitmapImage();
bi.CreateOptions = BitmapCreateOptions.DelayCreation;
bi.BeginInit();
if(parameter is int) {
bi.DecodePixelWidth = (int)parameter;
bi.DecodePixelHeight = (int)parameter;
}
bi.UriSource = new Uri(value.ToString());
bi.EndInit();
return bi;
}
}
} catch {
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
那它就不起作用了…但是为什么呢?