3

I have a Canvas with a Rectangle:

<Canvas>
   <Rettangle/>
</Canvas>

And I want that, when i resize my Canvas, the Rectangle keep the same relative position, for example:

----------------------------------------
|                                      |
|                                      |
|           ____                       |
|          |    |                      |
|          |____|                      |
|                                      |
|--------------------------------------


--------------------
|                   |
|   ___             |
|   |__|            |
|                   |
|-------------------

How can I do?

Simon Sarris
  • 62,212
  • 13
  • 141
  • 171
Nick
  • 10,309
  • 21
  • 97
  • 201

2 Answers2

5

Why not put the whole stuff in a Viewbox?

<Viewbox Stretch="Fill">
    <Canvas Width="400" Height="300">
        <Rectangle Canvas.Left="100" Canvas.Top="100" Width="100" Height="100" Fill="Blue"/>
    </Canvas>
</Viewbox>
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Why the `Canvas` has specific `Width` and `Height`? I want that `Canvas` fills all the available space inside my `Window`. – Nick Jun 23 '12 at 18:28
  • So if my Windows is resized I have to change the size of my Canvas dynamically? – Nick Jun 23 '12 at 18:59
  • You can give it any width and height you like. It just has to have a fixed size compared to the contained Rectangle. Canvas size and Rectangle size and position must have a certain pre-defined relation. You could as well set Canvas.Width=1.0 and Rectangle.Width=0.25. – Clemens Jun 23 '12 at 19:04
  • That's what the Viewbox does. Just try the sample XAML. Use the Viewbox as top-level container in a Window. – Clemens Jun 23 '12 at 19:05
1

The best possible solution is to create your own custom canvas and implement the re-sizing and re-positioning using some of the techniques mentioned in these questions -

How do you do relative positioning in WPF?

WPF: Setting the Width (and Height) as a Percentage Value

But for me this functionality looks very similar to zooming; in case your window is only having Canvas you can try to use following ZoomableCanvas from Kael Rowan and explicitly zoom-in/zoom-out when your window re-sizes:

http://blogs.msdn.com/b/kaelr/archive/2010/07/29/zoomablecanvas.aspx

Community
  • 1
  • 1
akjoshi
  • 15,374
  • 13
  • 103
  • 121