代码之家  ›  专栏  ›  技术社区  ›  santa

StaticResource标记扩展与System.Windows.Application.FindResource

  •  3
  • santa  · 技术社区  · 14 年前

    我在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();
         }
      }
    

    那它就不起作用了…但是为什么呢?

    1 回复  |  直到 14 年前
        1
  •  0
  •   santa    14 年前

    该死的我是愚蠢的…

    if(!string.IsNullOrEmpty(s) && File.Exists(s))
    

    文件。exists无法检查pack:/,,,-url的…所以它永远不会被评估…

    我想我必须结束这个问题…或者删除它…不知道该怎么做…