xamarin 了解宽度请求

lqfhib0f  于 2023-03-10  发布在  其他
关注(0)|答案(2)|浏览(114)

我想修改WidthRequest,因此我注意到这并没有真正设置元素的 width,而是一种提议。
示例:我将一个ListView作为子项添加到StackLayout。我正在为ListView设置WidthRequest,但结果不是我所期望的。

this.listView = new ListView
{
    ItemsSource = new List<IconMenu>
    {
        // creation of some entries
        // ...
    },
    ItemTemplate = new DataTemplate(typeof(IconMenuCell)),
    RowHeight = 44,
    // HERE is the problematic code!
    WidthRequest = 10,
};

Content = new StackLayout
{
    Orientation = StackOrientation.Horizontal,
    Children = {
        this.listView,
        this.detailView,
    },
};

这是IconMenuCell的结构/布局:

public IconMenuCell()
{
    var icon = new Image
    {
        Aspect = Aspect.AspectFit,
        WidthRequest = 40,
    };
    icon.SetBinding(Image.SourceProperty, "IconSource");

    this.textLabel = new Label {
        TextColor = Color.Gray,
        FontSize = 10,
        VerticalOptions = LayoutOptions.Center,
    };
    this.textLabel.SetBinding(Label.TextProperty, "Text");

    View = new StackLayout
    {
        Orientation = StackOrientation.Horizontal,
        Children =
        {
            icon,
            this.textLabel,
        },
    };
}

WidthRequest设置为10没有意义,因为图标本身应该为40,但这里我得到了整个列表视图的最小宽度。
如果我将WidthRequest设置为60或120,则没有区别。结果宽度相同(而且不是我想要的)。
WidthRequest在这里是如何工作的?我是否必须更改一些LayoutOptions

wtlkbnrh

wtlkbnrh1#

您需要指定HorizontalOptions,如“start”或“center”。stackLayout的默认horizontalOptions为FillAndExpand,因此即使您指定了宽度,列表视图等子元素也将填充整个可用水平区域。这是代表Microsoft进行的错误调用,因为默认行为将忽略/覆盖宽度请求。

下面是一个可视化示例:我有一个选择器,我设置宽度请求为200,这应该占用大约2/3的水平空间。

<StackLayout Padding="10">
    <Picker x:Name="pickerRanks" WidthRequest="200" />
</StackLayout>

正如您所看到的,宽度请求被覆盖/忽略。然后,在将HorizontalOptions设置为“Start”之后...

<StackLayout Padding="10">
    <Picker x:Name="pickerRanks" WidthRequest="200" HorizontalOptions="Start"/>
</StackLayout>

宽度请求被接受。当然我在这里设置的是.xaml文件中的属性,这是我通常喜欢的,但是你也可以像这样在C#中设置HorizontalOptions

pickerRanks.HorizontalOptions = LayoutOptions.Start;
uyhoqukh

uyhoqukh2#

WidthRequest只是描述了元素在下一个布局周期中所需的宽度。
要使其如您所期望的那样工作,必须满足两个条件:
1)请求的宽度与所有约束条件一致(例如,父项的宽度),并且
2)触发布局周期。
宽度请求:https://developer.xamarin.com/api/property/Xamarin.Forms.VisualElement.WidthRequest/
但这很复杂,我建议用网格代替堆栈布局,并将每个元素放在所需宽度的列中。
网格示例:https://developer.xamarin.com/api/type/Xamarin.Forms.Grid/

相关问题