views:

390

answers:

1

I'm using MVVM and am trying to databind the Source property of Image to my ViewModel in such a way that I can change the icon on the fly. What is the best pattern to follow for this? I still have the flexibility to change my ViewModel to suit, but I don't know where to start in either the xaml or ViewModel.

To be clear, I don't want my ViewModel to know about the specific images (that's for the View to know), just the state that triggers different images. For now I have just two states, lets say Red and Green. Should I create an Enum property or a bool? And then how do I databind to switch the image source?

+3  A: 

You can use a DataTrigger, and change the image (entirely in XAML) based on the value of a property in your ViewModel. I, personally, would use an enum, since you may want multiple states.

VisualStateManager will work for this as well, but will require WPF Futures or .NET 4.

In order to use a DataTrigger, you can do something like:

<Image>
  <Image.Style>
    <Style TargetType="Image">
      <Setter Property="Source" Value="1.png" />
      <Style.Triggers>
         <DataTrigger Binding="{Binding ViewModelEnumProperty}" Value="Image2">
             <Setter Property="Source" Value="2.png" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Image.Style>
</Image>

This will use "1.png", but when your enum is set to "Image2" in the VM, it'd switch to 2.png. More DataTriggers can be added as needed.

Reed Copsey
I am using .Net 4. Could you possibly elaborate on this at all? Maybe an example?
BrettRobi
I second Reed's solution. Use an enum in your viewmodel and a datatrigger in your view. http://msdn.microsoft.com/en-us/library/system.windows.datatrigger.aspx
emddudley
@BrettRobi: there you go
Reed Copsey
Perfect. Thanks Reed!
BrettRobi