I want to make a user control that shows an image and can invoke a command when clicked. Later I want to bind a list of these controls to a list of products.
Asked
Active
Viewed 4.3k times
5 Answers
57
Try this very straight forward approach
<Grid>
<Button Height="50" Width="50">
<Button.Template>
<ControlTemplate>
<Image Source="yourimage.png"/>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
private void Button_Click(object sender, RoutedEventArgs e)
{
// do smt
}

GibboK
- 71,848
- 143
- 435
- 658
-
2This was the most straight forward approach I've seen without having to override all the visual styles for the button. – jrandomuser Jul 10 '14 at 19:15
-
1I've gone with this approach, but reusability goes out the window, since you're effectively hard-coding in the image name. But, it fits my needs. – Lynn Crumbling Mar 10 '15 at 12:49
-
@jrandomuser see my answer then. – Khalil Khalaf Sep 13 '16 at 13:03
-
ok but no hover image ? it does not act as a real button here – Phil Nov 06 '19 at 20:28
8
Well, after a little more fiddling, a simple button does the job. Here it is:
<Button Command="{Binding Path=DisplayProductCommand}" >
<Image Source="..\Images\my-beautiful-product.jpg"/>
</Button>

mico
- 1,816
- 1
- 18
- 27
-
3This is not a clickable image, this is a button with an image inside it. I'm baffled that this is marked as the accepted answer. [This](http://stackoverflow.com/a/21597209/161250) should be the accepted answer. – Alex Jun 11 '15 at 07:04
4
There are several ways to do this, but one simple solution would be to use a button (maybe style away the border and background), and use the image as the content of the button.
You can later use a ListBox or similar, and override the DataTemplate to use the button and an image for each product.

code-zoop
- 7,312
- 8
- 47
- 56
-
This is in fact the first route I was taking, but I am wondering if there is a cleaner solution. – mico Apr 27 '10 at 12:51
4
<Image Name="imageFoo" Source="/AppFoo;component/Foo.png" Width="32" Cursor="Hand" MouseUp="imageFoo_MouseUp"/>
private void imageFoo_MouseUp(object sender, MouseButtonEventArgs e)
{
//Do something
}

Hong
- 17,643
- 21
- 81
- 142
-
4Sorry, mico, for not completely understanding your requirement. Let me leave my answer there just in case anyone needs a quick way to have a clickable image. – Hong Nov 29 '10 at 14:41
1
I don't know about you guys but PreviewMouseDown
and TouchUp
worked completely fine along with my binding:
<Image x:Name="bla" Source="{Binding blabla}" ... TouchDown="bla_TouchDown" PreviewMouseDown="bla_PreviewMouseDown">
I am using VS 2015

Khalil Khalaf
- 9,259
- 11
- 62
- 104