I need an irregularly shaped button in WPF. I am doing it in this way using XAML:
<Button Name="toggleButton" Click="toggleButton_Click" Canvas.Left="177" Canvas.Top="0">
<Button.Template>
<ControlTemplate>
<Image Source="ball.png" />
</ControlTemplate>
</Button.Template>
</Button>
My ball.png image is a PNG image with a ball with transparent area around it. The button displays correctly, but Click event handler is executed even when I clik on the transparent part of the image.
Is there any way to create irregular buttons using transparent PNGs?
Thanks, Michal
Michal, I wouldn't create a real "button". Just go to blend, get your image as an image brush into a rectangle, right-click make it a Button. If you are using Blend 4, this will generate the appropriate states in the Visual State Manager. You can get your mouse over, pressed, etc., to look like a button. Even disabled state.
Here's an example:
Now use the button as follows:
I know this is not using the transparent png as the button but it would be a much better alternative if you have the ability to convert the png to xaml.
You can create a class that inherits from Image and overrides HitTestCore so that it does not respond to hit testing over the transparent parts of an image, and then use that class in your template instead of a plain Image.
Here is an example, although the code to check for transparent pixels isn't very robust since it makes some assumptions about the image source and pixel format. If you already have code to check for transparent pixels then you should plug that in instead.