Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stretching a WPF Canvas Horizontally

How do I make a Canvas stretch fully horizontally with variable width? This is the parent Canvas, so it has no parents, only children.

XAML Source: it displays in blend http://resopollution.com/xaml.txt

like image 832
resopollution Avatar asked Jun 03 '09 19:06

resopollution


2 Answers

Use a Grid as the top level element in your UI - it'll stretch to fill its container. Then put a Canvas with HorizontalAlignment="Stretch" inside the Grid and it'll behave the way you want.

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Canvas Background="Blue"/>
</Grid>

That worked for me. The key is your top level UI element. While a Grid fills all available space by default, Canvases take up only as much room as their contents demand.

like image 146
James Cadd Avatar answered Sep 28 '22 00:09

James Cadd


I'm guessing you've tried
canvas.HorizontalAlignment = HorizontalAlignment.Stretch

If this doesn't work, then what you could do is bind the Width and Height properties of the canvas to the ActualWidth and ActualHeight properties of the containing window.

like image 34
Robin Avatar answered Sep 28 '22 01:09

Robin