Grid size doesn't bind to parent container's size

Viewed 113

I'm trying to bind the size of a Grid to the size of the parent container (Relativepanel with size on auto, named 'MainPanel') in the XAML of a Page like this:

<Grid Width="{Binding ElementName=MainPanel, Path=ActualWidth}">

After doing so, it works in the Designer, but as soon as I run the App it shrinks again (and does so in the Designer).

I've also tried:

<Grid Width="{Binding ActualWidth, ElementName=MainPanel}">

And removed all of my code interacting with the controls.

What is the problem here? (Universal Windows App in VS 2019)

2 Answers

Yep, I saw this problem, it does not work within UWP platform, but works well in WPF platform. please refer ActualHeightProperty remark part

Although it has an ActualHeightProperty backing field, ActualHeight does not raise property change notifications and it should be thought of as a regular CLR property and not a dependency property.

For your requirement, you could use Microsoft.Toolkit FrameworkElement Extensions to make actual size binding avaiable.

Install Microsoft.Toolkit.Uwp.UI.Controls nuget, then set extension like the following

xmlns:ui="using:Microsoft.Toolkit.Uwp.UI"
......
<RelativePanel
    x:Name="MainPanel"
    ui:FrameworkElementExtensions.EnableActualSizeBinding="True"
    SizeChanged="MainPanel_SizeChanged">
    <Grid
        Width="{Binding ElementName=MainPanel, Path=(ui:FrameworkElementExtensions.ActualWidth)}"
        Height="100"
        Background="SeaGreen" />
</RelativePanel>

For more detail please refer this tutorial.

Related