0

I have an application written in WPF MVVM. I want to initialize an embedded image from XAML (so that I can see it in the designer) but also bind it to the ViewModel so I can manipulate from code. I can successfully initialize it like this:

<Image x:Name="Image1" Source="pack://application:,,,/images/image1.png" Height="200" Width="55"  Opacity="0.35">

How do I bind it to the ViewModel?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Tim Hansson
  • 309
  • 2
  • 16

2 Answers2

2

If you want to see some data in design time you can define DesignTime viewmodel.

<Window
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type=designTimeViewModels:DesignViewModel,
                                                       IsDesignTimeCreatable=True}"
/>

And to Bind Image Source use folowing code:

<Image Source="{Binding DisplayedImagePath}" />

ViewModel:

public string DisplayedImagePath 
{
    get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}

from this topic: Binding an Image in WPF MVVM

Community
  • 1
  • 1
Spirosi
  • 324
  • 1
  • 15
  • @Timbooo Manipulation of Image object in VM violates MVVM basic principles. You should do this in your View (Code behind.). Use Events to trigger some action from VM in your View. Messenger if you are using MVVM light, or EventAggregator in PRISM. Register Event in your VM code and Subscribe in your View (code behind). But don't forget to unregister it to avoid memoryleaks ;) – Spirosi May 18 '15 at 12:53
  • I am aware of that. =) I keep my codebehind extremely thin, I only declare the constructor where I bind my ViewModel. My view-bindings are in the ViewModel, and I keep my business logic in the Models. I was looking for some way to bind an image property in the ViewModel to an image in the View, instead of binding a string property to the source property of the image. Maybe it this is not possible? – Tim Hansson May 22 '15 at 20:26
0

You could use FallbackValue...

    <BitmapImage x:Key="Image1" UriSource="pack://application:,,,/images/image1.png" />

    <Image x:Name="Image1" Source={Binding Image1, FallbackValue={StaticResource Image1}}" />

This has the possible downside of having your image how up at run time if the conditions for use of the fallback value is triggered; so you would need to avoid that situation.

glenebob
  • 1,943
  • 11
  • 11