WPF Image.Source Data File in MVVM

I am using MVVM and trying to bind the original Image property to my ViewModel so that I can change the icon on the fly. What is the best sample for this? I still have the flexibility to change my ViewModel model, but I don't know where to start in xaml or ViewModel.

To be clear, I don't want my ViewModel to know about specific images (what you need to know for a view), just a state that triggers different images. At the moment, I have only two states, one can say red and green. Should I create an Enum or bool property? And how do I configure the binding to the image source?

+7
data-binding wpf mvvm
source share
1 answer

You can use a DataTrigger and change the image (completely in XAML) based on the value of the property in the ViewModel. I personally used the listing, as you may need several states.

VisualStateManager will also work for this, but it will require WPF Futures or .NET 4.

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 listing is set to "Image2" in the virtual machine, it will switch to 2.png. If necessary, add more DataTriggers.

+10
source share

All Articles