
Setting Binary Resources in Code
You have seen how to access embedded resources in XAML using the Source value of the Image control.
Although many UI controls can use XAML to assign resources, sometimes you will need to do so
programmatically. This can be helpful if you need set an image based on user preferences, or need to load the
data from the user’s machine via isolated storage.
Assume the updated UserControl. Notice that the Image controls no longer have a Source attribute. Also
notice the code contains a Button type and handles the Click event.
<UserControl x:Class="SLResourcesGraphicsAnim.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="500">
<StackPanel x:Name="LayoutRoot" Background="White">
<Image x:Name = "imgNorthShore" Height="300"/>
<Image Height = "100" Width = "138" x:Name = "NorthShoreRadio"/>
<Button Name = "btnLoadResources" Height = "40" Width = "100"
Content = "Load Resources" Click = "btnLoadResources_Click"/>
</StackPanel>
</UserControl>
Here is the Click event hander that sets the Source property of each Image. Note the Source property expects
a System.Windows.Media.Imaging.BitmapImage object. Also notice that the code makes use of the
System.Uri type to define the relative or absolute path to the resource.
// C# (VB code is similar).
private void btnLoadResources_Click(object sender, RoutedEventArgs e)
{
// Load the embedded file. The assumption here
// is that Build Action = Resource.
this.imgNorthShore.Source = new BitmapImage
(new Uri("MyImages/SplitRock.jpg", UriKind.Relative));
// Load the HTTP-based resource.
this.NorthShoreRadio.Source = new BitmapImage
(new Uri("http://www.wtip.org/images_035.jpeg",UriKind.Absolute));
}
Binary Resources in Code
Table of Contents
Copyright (c) 2008. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an
online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.
Courseware
Training Resources
Tutorials
Services