Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ImageSource allowed as a WPF Resource?

Tags:

resources

wpf

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?

like image 548
Gishu Avatar asked Nov 07 '10 07:11

Gishu


People also ask

What default resources are supported in WPF?

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.


1 Answers

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.

like image 87
Tergiver Avatar answered Oct 05 '22 19:10

Tergiver