我在ResourceDictionary中定义了一个BitmapImage:
<BitmapImage x:Key="Skin_Image_Back" UriSource="./images/back.png" />
并加载了像那个
的ResourceDictionaryvar 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,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();
}
}
然后它不起作用......但是为什么?
答案 0 :(得分:0)
if(!string.IsNullOrEmpty(s) && File.Exists(s))
File.Exists无法检查pack:// ,,, - URL的......所以它永远不会被评估...
认为我必须关闭这个问题......或者删除它......不知道该怎么做......