Why does this line in a ResourceDictionary not result in a compile-error?
<Window.Resources>
<ResourceDictionary>
<ImageSource x:Key="aKey">SomePath</ImageSource>
</ResourceDictionary>
</Window.Resources>
My understanding was that this would result in an instance of ImageSource being created using the default ctor. This would be followed by setting all the specified properties.
However ImageSource is an abstract class - so why doesn't this result in a compile error?
WPF supports different types of resources. These resources are primarily two types of resources: XAML resources and resource data files. Examples of XAML resources include brushes and styles. Resource data files are non-executable data files that an application needs.
Try this bit of XAML:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<ResourceDictionary>
<Window x:Key="aKey">BlogHeader.jpg</Window>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Image Source="{StaticResource aKey}"/>
</Grid>
</Window>
It compiles just fine, but when you run it you get a runtime XamlParseException:
Cannot convert the value in attribute 'Source' to object of type 'System.Windows.Media.ImageSource'.
If you try using a simple type instead of Window
, for example:
public class SomeType
{
}
You will get a compile-time error:
The Element type 'WpfApplication1.SomeClass' does not have an associated TypeConverter to parse the string 'BlogHeader.jpg'
So the answer lies in the TypeConverter
provided by ImageSource
which is ImageSourceConverter
. The magic happens in ImageSourceConverter.ConvertFrom
which takes a string, creates an Uri
from it, and uses BitmapFrame.Create
to create a BitmapFrame
which is derived from ImageSource
.
Note that I used Window
in the first example only to use a type that provides a type converter from a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With