11

This seems like such a simple question, but I have been trying for an hour and can't seem to figure it out.

All I want to do is fill the MainWindow with a Canvas. I couldn't find any properties to allow this, and the only way I could think of to do it is to set Canvas.Width/Height = MainWindow.Width/Height, but I would have to do that every time the window is resized.

In WinForms docking an element in a parent container was easy.

Eric
  • 2,098
  • 4
  • 30
  • 44

4 Answers4

21

Just set the Canvas.HorizontalAlignment and VerticalAlignment to "Stretch". This will cause the Canvas to fill the space available from it's containing UI element. Just make sure to NOT specify Width/Height explicitly.

In XAML, this is just:

<Window ...Other window props... >
    <Canvas HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <!-- Canvas items here... -->
    </Canvas>
</Window>
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
3

put this for your canvas width and height in xaml.

Width="{Binding Path=ActualWidth, ElementName=Window1}"
Height="{Binding Path=ActualHeight, ElementName=Window1}"

it should change accordingly when you resize the window

devman
  • 1,529
  • 2
  • 11
  • 24
  • 2
    How is this better? I think Eric's answer is more simple / robust than doing this kind of binding. – RQDQ Jan 12 '11 at 18:17
3

In WPF you can do docking by placing your items inside a DockPanel and using the Dock inherited property. However, if you want the entire Window to be a Canvas, just make it so the Window's content is the canvas, and not another kind of panel:

<Window ...>
    <Canvas>
        <!-- blah blah -->
    </Canvas>
</Window>
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
0

Nevermind, it seems you have to add a DockPanel:

<DockPanel Name="dockPanel1">
    <Canvas Name="canvas1" Background="White"></Canvas>
</DockPanel>
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Eric
  • 2,098
  • 4
  • 30
  • 44
  • There are many ways to do this. This one is a bit overkill, but will work fine. – RQDQ Jan 12 '11 at 18:15
  • 2
    Tip: don't leave those auto-generated names on your controls. Give them meaningful names. You'll be happier when you don't have to check if the license plate number is in textBox23 or textBox17. Better yet, don't name them at all if you don't need to refer to them: in WPF names are optional. – R. Martinho Fernandes Jan 12 '11 at 18:17
  • @Martinho, I didn't know names were optional. That is convenient. Thanks. – Eric Jan 12 '11 at 18:18