1

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.

ASh
  • 34,632
  • 9
  • 60
  • 82
Shawn Miller
  • 79
  • 1
  • 7

3 Answers3

5

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.

Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Good answer by @Clemens. Note that you will most likely stumble upon issues due to the "pack Uris in WPF", but don't worry, Clemens got that covered as well: http://stackoverflow.com/a/14859050/27083 – tobsen Oct 05 '13 at 17:44
  • @Clemens, how about a byte array instead of an ImageSource? Then we can use a value converter to get a bitmapimage out of it. – wingerse Apr 01 '16 at 22:49
  • byte array is also automatically converted to ImageSource. – Clemens Apr 01 '16 at 23:21
1

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.

Will Custode
  • 4,576
  • 3
  • 26
  • 51
1

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.

Rajiv
  • 1,426
  • 14
  • 21