0

I have the following XAML code in a windows store app:

    <Canvas HorizontalAlignment="Left" VerticalAlignment="Top" x:Name="capturePreviewCanvas" Width="774" Margin="288,48,0,0" Height="688">
        <CaptureElement x:Name="capturePreviewCaptureElement" Canvas.Left="10" Canvas.Top="10"/>
    </Canvas>

I have the CaptureElement's width and height set to autosize and I expected it to fill the entirety of the parent Canvas but that doesn't appear to be how it works. If I set the size to Auto it simply fills the same size area, even if that area is larger than the parent Canvas (which I didn't think was possible).

Example: Canvas is 500x500, Autosize CaptureElement sizes itself to around 600x600, exceeding the bounds of its parent Canvas.

Why does this happen and how do I get the CaptureElement to always autosize to Fit or Fill its parent Canvas?

Sheridan
  • 68,826
  • 24
  • 143
  • 183
Giardino
  • 1,367
  • 3
  • 10
  • 30

1 Answers1

2

You need to understand that not all WPF Panels have the ability to alter the size of their children automatically. You can find out which Panels can and can't resize their children in the Panels Overview page on MSDN, but in short, StackPanels, WrapPanels and Canvass do not resize their children automatically while Grids and DockPanels can.

However, when using a Panel that cannot automatically resize its children, there is a trick that you can employ. You can simply data bind the dimensions of your CaptureElement to those of the parent Canvas:

<CaptureElement x:Name="capturePreviewCaptureElement" Canvas.Left="10" Canvas.Top="10"
    Width="{Binding ActualWidth, ElementName=capturePreviewCaptureElement}"
    Height="{Binding ActualHeight, ElementName=capturePreviewCaptureElement}" />

Of course, if you set the Canvas.Left and Canvas.Top properties to non zero values, then this will in fact make the CaptureElement even larger than the parent Canvas.

Sheridan
  • 68,826
  • 24
  • 143
  • 183