Neil Hobson
Neil Hobson

Reputation: 515

How do I keep the positions of my Buttons the same on a Canvas?

I have a WPF Window that has a Image in the background as a canvas. It is a picture of a pirate ship. I want to have buttons attached to certain points on the image which stay the same even if the size of the window is altered. With a fixed Window size this is fine. Can I select Hotspots at all where my Buttons will stay in touch with the same position on the image? Or do I use percentage positioning for the buttons?

This may be a lot to ask of WPF.

The buttons are on top of the canvas.

Thanks

Upvotes: 0

Views: 124

Answers (2)

Mike Strobel
Mike Strobel

Reputation: 25623

You could take a common ancestor of the canvas and buttons, give it a fixed size, and wrap it in a Viewbox. Then you can let the Viewbox take care of scaling for you. The entire scene--buttons, image, and anything else--will be scaled together, so you won't need to manually adjust any positioning.

Upvotes: 0

Rachel
Rachel

Reputation: 132558

Assuming your Background Image stretches according to Window Size, I'd use a Converter and set Canvas.Top and Canvas.Left based on a percentage.

You could either code your own IValueConverter that accepts the Canvas.Height and Canvas.Width, and a ConverterParameter identifying what percentage you want of the value, or I have a fairly generic Math Converter on my blog that you are free to use if you prefer.

<Button Canvas.Top="{Binding ElementName=MyCanvas, Path=ActualHeight, Converter={StaticResource MathConverter}, ConverterParameter=@VALUE*.25}"
        Canvas.Left="{Binding ElementName=MyCanvas, Path=ActualWith, Converter={StaticResource MathConverter}, ConverterParameter=@VALUE*.25}" 
        ... />

(I forget if Height/Width or ActualHeight/ActualWidth is the more accurate value - you may need to test that one)

Upvotes: 2

Related Questions