【发布时间】:2010-07-30 08:32:59
【问题描述】:
我在我的 ResourceDictionary 中定义了一个 BitmapImage:
<BitmapImage x:Key="Skin_Image_Back" UriSource="./images/back.png" />
然后像这样加载 ResourceDictionary
var dict = Application.LoadComponent(
new Uri("TestProject.DefaultStyle;component/Style.xaml",
UriKind.Relative)) as ResourceDictionary;
Application.Current.Resources.MergedDictionaries.Add(dict);
当我通过 xaml 和静态资源标记扩展分配图像时
<Image Source="{StaticResource Skin_Image_Back}" />
一切正常。
但是当我想通过源设置图像时:
MyObject.ImageUrl = FindResource("Skin_Image_Back").ToString();
FindResource 返回一个 URI,ToString 的结果是
"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();
}
}
那么它不起作用......但是为什么?
【问题讨论】: