【问题标题】:StaticResource Markup Extension vs. System.Windows.Application.FindResourceStaticResource 标记扩展与 System.Windows.Application.FindResource
【发布时间】: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();
     }
  }

那么它不起作用......但是为什么?

【问题讨论】:

    标签: c# .net wpf image


    【解决方案1】:

    我是不是傻了……

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

    File.Exists 无法检查 pack://,,,-URL 的...所以它永远不会被评估...

    认为我必须关闭问题...或删除它...不知道该怎么办...

    【讨论】:

      猜你喜欢
      • 2011-03-11
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 2012-02-01
      • 2016-08-13
      • 2011-02-13
      相关资源
      最近更新 更多