StaticResource and System.Windows.Application.FindResource markup extension

I defined BitmapImage in my ResourceDictionary, like this:

<BitmapImage x:Key="Skin_Image_Back" UriSource="./images/back.png" />

and loaded a ResourceDictionary like this

var dict = Application.LoadComponent(
   new Uri("TestProject.DefaultStyle;component/Style.xaml",
   UriKind.Relative)) as ResourceDictionary;
Application.Current.Resources.MergedDictionaries.Add(dict);

when I assign an image via xaml and a StaticResource markup extension like

<Image Source="{StaticResource Skin_Image_Back}" />

everything is working fine.

but when I want to install the image from the source via:

MyObject.ImageUrl = FindResource("Skin_Image_Back").ToString();

FindResource returns a URI that ToString results in

"pack://application:,,,/TestProject.DefaultStyle;component/images/back.png"

which is associated with the converter, for example

<Image Source="{Binding ImageURL, Converter={StaticResource StringToImageThumbSourceConverter}}" />

which is implemented as

<Converter:StringToImageThumbSource x:Key="StringToImageThumbSourceConverter" />

and

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

then it won’t work ... but WHY?

+3
source share
1 answer

Damn, I'm dumb ...

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

File.Exists cannot check the package: // ,, - URL ... so it is never evaluated ...

, ... ... , ...

0

Source: https://habr.com/ru/post/1757297/


All Articles