Docking/Filling in WPF

Eric picture Eric · Jan 12, 2011 · Viewed 20.3k times · Source

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.

Answer

Reed Copsey picture Reed Copsey · Jan 12, 2011

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>