dynamically updating image source

Hi, I want to change an image source based on a property in a class. I want the image to update as soon as the property changes.

As a simple example, say the property is just an integer. When it changes, I want the image source to change to 1.gif.

It seems like this should be very easy, yet there is no clear tutorial on it and a lot of conflicting information. A very small example would be greatly appreciated. Thanks!

[431 byte] By [DrMario] at [2008-1-8]
# 1

This is certainly possible, here's a small example to demonstrate.

Code Snippet

<Window x:Class="DynImageSourceTest.Window1"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="Window1" Height="240" Width="320">

<Grid>

<Grid.RowDefinitions>

<RowDefinition Height="*" />

<RowDefinition Height="20" />

</Grid.RowDefinitions>

<Image Grid.Row="0">

<Image.Style>

<Style TargetType="Image">

<Setter Property="Source" Value="1.png" />

<Style.Triggers>

<DataTrigger Binding="{Binding ElementName=_slider, Path=Value}" Value="2">

<Setter Property="Source" Value="2.png" />

</DataTrigger>

</Style.Triggers>

</Style>

</Image.Style>

</Image>

<Slider Name="_slider" Minimum="1" Maximum="2" Grid.Row="1" IsSnapToTickEnabled="True"/>

</Grid>

</Window>

What we have here is an image with a DataTrigger that changes the value of a binding on Image.Source based on the value of a slider. Add two images to your project as resources (this example uses 1.png and 2.png), then run the application and slide the slider left and right. When the value of the slider is "2", the image "2.png" will be displayed. When the value of the slider is "1", the "1.png" image will be displayed.

I hope this helps!

-Mike

MichaelCook-MSFT at 2007-10-2 > top of Msdn Tech,Visual Studio Orcas,Windows Presentation Foundation (WPF)...
# 2
This works great! Do you suppose it is more technically proper to use triggers instead of just binding the Image Source directly?
DrMario at 2007-10-2 > top of Msdn Tech,Visual Studio Orcas,Windows Presentation Foundation (WPF)...
# 3

Glad it worked for you. Neither way is necessarily more technically proper, but this is a pure XAML solution. The alternative you describe would require an additional DependencyProperty which you would set by some other means.

-Mike

MikeCook-MSFT at 2007-10-2 > top of Msdn Tech,Visual Studio Orcas,Windows Presentation Foundation (WPF)...

Visual Studio Orcas

Site Classified