Reputation: 136683
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?
Upvotes: 6
Views: 1147
Reputation: 14517
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.
Upvotes: 4