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

如何在XAML中设置视图宽度为父容器的百分比?

解决方案

方法一:改用Grid布局(推荐)

*比例语法是Grid布局的专属特性,直接把外层的AbsoluteLayout换成Grid,通过ColumnDefinitions设置比例就能轻松实现需求,代码修改如下:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SnipSnip.SnippetsPage"
             Title="SnippetsPage">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="0.2*"/>
            <ColumnDefinition Width="0.8*"/>
        </Grid.ColumnDefinitions>
        <ListView x:Name="SnippetsListView" Grid.Column="0">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Text="{Binding Name}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Editor Grid.Column="1"/>
    </Grid>
</ContentPage>

方法二:在AbsoluteLayout中使用相对约束

如果坚持使用AbsoluteLayout,可以通过AbsoluteLayout.LayoutBounds属性设置相对父容器的宽度比例,无需后台代码:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SnipSnip.SnippetsPage"
             Title="SnippetsPage">
    <AbsoluteLayout>
        <ListView x:Name="SnippetsListView"
                  AbsoluteLayout.LayoutBounds="0, 0, 0.2, 1"
                  AbsoluteLayout.LayoutFlags="WidthProportional, HeightProportional">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Text="{Binding Name}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Editor AbsoluteLayout.LayoutBounds="0.2, 0, 0.8, 1"
                AbsoluteLayout.LayoutFlags="WidthProportional, HeightProportional"/>
    </AbsoluteLayout>
</ContentPage>

这里的LayoutBounds参数依次是:X坐标、Y坐标、宽度比例、高度比例;LayoutFlags指定哪些维度使用相对比例计算。

补充说明

除了上述两种方式,也可以通过绑定父容器的Width属性并使用转换器来实现,但前两种方法在XAML中就能完成,更简洁直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:10:26