Wednesday, November 3, 2010

WPF - Accessing assembly Resources in XAML

In this post, we will be discussing how to access elements from assembly resources. We will be using Pack Uri syntax to access a resource from assembly. Lets use this image as a resource for our first example.


You would have to add this image to the project in order to make it an assembly resource. After adding it, just right click it and specify Build Action as Resource after taking its properties.


In this post, I want to discuss how we can access assembly resources. We would be defining an image as "Resource" and access it in XAML. In the following example, we are accessing the same image as added above. You can see that we can use pack uri syntax to access assembly resources. To display image, we have used Image element. Although most people still call it a Control out of habit but technically Image is not a control in WPF, it is rather FrameworkElement. It is funny because msdn also has this description about it:

"Represents a control that displays an image."
<Window x:Class="WpfApplication4.Window3"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window3" Height="400" Width="500">
<StackPanel>
<Image Source="pack://application:,,/1.jpg" />
</StackPanel>
</Window>

When we run the application, it appears as follows. You can see that it has successfully loaded the image in the Image



Accessing items from other assemblies:
Now we want to discuss how to access items from other assemblies. Lets create a separate project, add an image as Resource in this. Reference this project to the first project. Lets use the image of Mohatta Palace museum at Karachi.


Add this to a new project and specify Build Action as Resource. We update the view in the first project as follows:
<Window x:Class="WpfApplication4.Window3"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window3" Width="500" Height="500">
<StackPanel>
<Image Source="pack://application:,,/1.jpg" Height="250" />
<Image Source="pack://application:,,,/WpfApplication5;component/4.jpg" />
</StackPanel>
</Window>

Please pay special attention to the pack uri syntax used to access resource from other assembly. It is roughly as follows:

pack://application:,,,/OTHER_ASSEMBLY;component/OTHER_RESOURCE.RESOURCE_EXTENSION

When we run this, it appears as follows:

No comments: