Dynamic Image Binding in WPF

Yesterday I was asked to deploy a registration system that has a configurable background image. The application was to be developed in WPF. My Solution? Include the filename of the image in the app.config file of the application. So, next time, when a registration system is needed, my fellow teammates or the team that needs the system will just set the location of the background in the config file.

App.config


<?xml version="1.0"?>
<configuration>
 <startup>
 <supportedRuntime version="v2.0.50727"/>
 </startup>
 <appSettings>
 <add key ="imageLocation" value ="front.jpg"/>
 </appSettings>
</configuration>

RegistrationForm.xaml.cs


void RegistrationForm_Loaded(object sender, RoutedEventArgs e) {
 string myPath = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + ConfigurationSettings.AppSettings["imageLocation"].ToString();
 Uri myUri = new Uri(myPath.Replace(@"\",@"/"));
 BitmapImage bi = new BitmapImage(myUri);
 imgPath.SetValue(Image.SourceProperty, bi);
 }

RegistrationForm.xaml


<Window x:Class="Summer09Launch.RegistrationForm"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 Title="RegistrationForm" Height="800" Width="1280" WindowStyle="None" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" ScrollViewer.VerticalScrollBarVisibility="Disabled" Topmost="True" x:Name="RegistrationForm">

<Grid x:Name="grdOne">

<Image Margin="0,0,0,0" Stretch="Fill" Width="1280" Height="800" x:Name="imgPath"/>

</Grid>

</Window>

The Output

front_micro

Change the appSettings section in the App.config file

<appSettings>
 <add key ="imageLocation" value ="newBackground.jpg"/>
</appSettings>

Output after setting the new filename.

newBackground

Note

The above technique also works on silverlight.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: