WPF Force UserControl to expand to fill maximal render size

5.5k views Asked by At

I need to create a UserControl, which is hosted within a "parent" ContentControl who is set with "Center" Horizontal and Vertical alignment.

This control hosts another "child" UserControl, which I would like to be as big as it can get without stretching over the render-able size.

I noticed that if I set the child's size to be bigger than the render-able size, i get the size I want as a "DesiredSize" property on that control. However I don't see how can I get that information without oversizing the control.

I've created this sample to illustrate the situation, I want "ChildControl"'s pink background to stretch over the entire window.

Just to clarify, I only have control on "ControlableElementA" and "ControlableElementB" I cannot bind to the main window, in the actual application I use this as an embedded window with varying levels of hierarchy in between..

The "ChildControl" and "ParentControl" are beyond my reach due to constraints above me.

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="300" Width="300">
    <Grid>
        <ContentControl Name="ParentControl" HorizontalAlignment="Center" VerticalAlignment="Center">
            <Grid Name="ControlableElementA" Background="Black" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                <ContentControl Name="ControlableElementB">
                    <Grid Name="ChildControl" Background="Pink" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                        <Button Width="30" Height="30"></Button>
                    </Grid>
                </ContentControl>
            </Grid>
        </ContentControl>
    </Grid>
</Window>

Thanks ahead, I apologize if the description is a little cryptic

1

There are 1 answers

1
Mike Eason On

HorizontalAlignment and VerticalAlignment as Stretch means "Stretch to the maximum size within the bounds of the parent container."

However, your parent container is set to Center, which means your UserControl effectively has an Auto width and height.

To fix this, simply remove:

HorizontalAlignment="Center" VerticalAlignment="Center"

From the ContentControl.