Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF databind Image.Source in MVVM

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?

like image 289
BrettRobi Avatar asked Mar 28 '10 01:03

BrettRobi


1 Answers

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.

like image 156
Reed Copsey Avatar answered Oct 20 '22 21:10

Reed Copsey