Search code examples
wpfxamluwpxaml-islands

How can we show UWP user control on vertical-top edge of the parent window?


Following XAML in this Microsoft tutorial is showing too much gap between the top edge of the parent window and the UWP user control. Question: How can we make the user control align to the top edge of parent window? Remark: The VerticalAlignment="Top" in the StackPanel below does not help. This question is something similar to this post but in a different context.

<UserControl
    x:Class="ClassLibUWP_inside_WPF.MyUserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ClassLibUWP_inside_WPF"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:winui="using:Microsoft.UI.Xaml.Controls"
    mc:Ignorable="d"
    d:DesignWidth="400" Height="329">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="211*"/>
            <ColumnDefinition Width="189*"/>
        </Grid.ColumnDefinitions>
        <StackPanel Background="LightCoral" Grid.ColumnSpan="2">
            <TextBlock>This is a simple custom UWP control</TextBlock>
            <Rectangle Fill="Blue" Height="93" Width="100"/>
            <TextBlock Text="{x:Bind XamlIslandMessage}" FontSize="50"></TextBlock>
            <winui:RatingControl Height="32" />
        </StackPanel>
    </Grid>
</UserControl>

When you run the app built in the above tutorial, you get the following screen showing the above UWP user control:

enter image description here

I would instead like to display it as follows [notice about no gap between window title and the red stack panel]:

enter image description here


Solution

  • The UserControl has a fixed height that is smaller than the height of the window and thus is vertically centered in the window. Setting VerticalAlignment="Top" on the WindowsXamlHost should give what you want.