You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UNO WinUI3中UserControl无法填充父容器的问题

解决Uno WinUI 3中UserControl无法填满父容器的问题

要让你的ExampleControl填满父容器的可用空间,只需在UserControl标签上添加HorizontalContentAlignment="Stretch"和VerticalContentAlignment="Stretch"属性,修改后的代码如下:

<UserControl
    x:Class="UserControlScaling.Views.ExampleControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UserControlScaling.Views"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Stretch"
    HorizontalContentAlignment="Stretch"
    VerticalContentAlignment="Stretch">
  <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <Border BorderBrush="Red" BorderThickness="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
      <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <TextBlock Text="This button does absolutely nothing" HorizontalAlignment="Center"/>
        <Button Content="This is a button" HorizontalAlignment="Center"/>
      </Grid>
    </Border>
  </Grid>
</UserControl>

原因说明

UserControl的默认模板中,内部的ContentPresenter默认HorizontalAlignment为Left、VerticalAlignment为Top,这会导致它只给内部内容分配刚好容纳子元素的空间。即使你给UserControl和内部的Grid设置了Stretch,如果不修改ContentPresenter的对齐方式,内部内容依然无法填满整个UserControl的区域。添加HorizontalContentAlignment和VerticalContentAlignment属性,本质是修改了内部ContentPresenter的对齐行为,让它拉伸填满UserControl的可用空间,进而带动内部的Grid和Border也填满整个区域。

另外,你的MainPage中的ContentControl可以简化,直接放置ExampleControl在Grid里即可,Grid的子元素默认会拉伸填满空间:

<Page x:Class="UserControlScaling.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:UserControlScaling"
      xmlns:utu="using:Uno.Toolkit.UI"
      xmlns:um="using:Uno.Material"
      xmlns:views="using:UserControlScaling.Views"
      Background="{ThemeResource BackgroundBrush}">
  <Grid BorderBrush="Green" BorderThickness="2">
    <views:ExampleControl/>
  </Grid>
</Page>

内容的提问来源于stack exchange,提问作者Tlaloc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:27:32