Home > Software design >  How does UWP XAML recognize ImageSource conversion from string
How does UWP XAML recognize ImageSource conversion from string

Time:09-17

The following is a perfectly valid XAML:

<Image Width="50" Height="50" Source="/Assets/StoreLogo.png" />

The question is, how does UWP knows about converting this string to an ImageSource. I was expecting to see something like IValueConverter interface or CreateFromString attribute.

But these are the only attributes I can see:

enter image description here

CodePudding user response:

How does UWP XAML recognize ImageSource conversion from string

ImageSource is dependency property for Image control, it means that you could convert it to BitmapImage in the PropertyChangedCallback method.

When the source property changed, it will call the callback method, you could make BitmapImage with string url like the following. For explain this you could make a custom Dependency property.

imageHolder.Source = new BitmapImage(new Uri("ms-appx:///local/test.png"));

Dependency

public static readonly DependencyProperty UriProperty = DependencyProperty.Register(
  "Uri",
  typeof(String),
  typeof(CustomImage),
  new PropertyMetadata(null,new PropertyChangedCallback(OnUriChanged))
);

And please note Image is sealed type, you can't make a class derive from it

CodePudding user response:

Hard-coded image path is to be converted to bitmap in compile time, so no String-to-ImageSource conversion is fulfilled in run-time. For the dynamicly specified path strings through {x:Bind}, UWP uses XamlBindingHelper.ConvertValue() in code behind (auto-generated *.g.cs file in obj folder). Maybe XAML parser would be using something similar internally. If you'd like to take the same approach, try following code:

theImage.Source = XamlBindingHelper.ConvertValue(typeof(ImageSource), "/Assets/StoreLogo.png") as ImageSource;
  • Related