I'm trying to use WinUI3 with MVVM. For that case, I'm using a Content Control to bind the view model. But the Content Control seems to break automatic resize of the inner Grid. So I'm trying to bind the grid to the window size, but this does not work properly, when the window size changes.
<Window
x:Class="TimePunch_WinUI_StackedUI_Demo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TimePunch_WinUI_StackedUI_Demo"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:stackedUi="using:TimePunch.StackedUI"
Title="MainWindow"
x:Name="Window"
mc:Ignorable="d">
<ContentControl DataContext="{Binding Source={StaticResource ViewModelLocator}, Path=MainWindowViewModel}">
<Grid Width="{Binding ElementName=Window, Path=Bounds.Width}"
Height="{Binding ElementName=Window, Path=Bounds.Height}">
Any ideas, what I'm doing wrong ?
First of all, you can't expect resizing by binding to Width
or Length
. Usually, they are regular properties and not DependencyProperties
which notify the UI when their values change.
Secondly, the ContentControl
, by default, should be already stretched inside the Window
. Try the code below and you'll see that the text is centered horizontally and vertically.
<Window
x:Class="WinUIApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:WinUIApp"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<ContentPresenter
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Content="WinUI" />
</Window>
You can also confirm this by placing your mouse on the [ContentPresenter] in the Live Visual Tree.