Shawn Miller
Shawn Miller

Reputation: 79

How to do Image binding in MVVM style?

I am trying to have a button with an image and text and use bindings to my ButtonCommandViewModel. What kind of property do I need in my ButtonCommandViewModel for the Image to bind to that would adhere to the MVVM concept? Should I just have an Image, or a URL, or some kind of string that the Image tag can run through a converter?

 <Button Command="{Binding Command}">
     <Button.ContentTemplate>
         <DataTemplate>
             <StackPanel>
                 <Image />
                 <TextBlock Text="{Binding DisplayName}" />
             </StackPanel>
         </DataTemplate>
     </Button.ContentTemplate>
 </Button>

The above xaml is what I'm trying to use for an item template.

Upvotes: 1

Views: 4760

Answers (3)

Clemens
Clemens

Reputation: 128013

You'll have to bind the Image control's Source property, which is of type ImageSource.

WPF has built-in type conversion from string, Uri and byte[] to ImageSource without the need for a binding converter.

As long as your images can be created from URI strings or byte arrays (containing an encoded bitmap frame, e.g. a PNG), you could choose which property type you prefer. string might be the most simple one, but the others are also perfectly legal.

However, when your ViewModel creates images dynamically, ImageSource (or a derived type) usually is the more appropriate option without using a binding converter.

Upvotes: 5

Rajiv
Rajiv

Reputation: 1456

Yes, use Uri/string (I prefer Uri) to databind the Image.Source property.

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

In addition to that keep the following points in mind. 1. When you add an image to the project make sure the Build action is set to "Resource". 2. If you want to access image from another project use pack Uri.

Upvotes: 1

Will Custode
Will Custode

Reputation: 4594

You should use just a Uri. You want to seperate the UI from the data, so don't put controls in the ViewModel. That's what I was taught, at least.

Upvotes: 1

Related Questions