Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

xamarin - Understanding WidthRequest

I want to change the WidthRequest. Thereby I noticed that this doesn't really set the width of an element. Rather it is kind of a proposal.

Example: I have a ListView added as child to a StackLayout. I'm setting a WidthRequest for the ListView, but the result is not what I expect.

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,
    },
};

This is the structure/layout of 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,
        },
    };
}

Setting the WidthRequest to 10 doesn't make sense, because the icon itself should take 40. But here I get the smallest width for the whole list view.

There is no difference if I set WidthRequest to 60 or 120. The resulting width is the same (and not what I want).

How does WidthRequest work here? Do I have to change some LayoutOptions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

WidthRequest just describes an element's desired width during the next layout cycle.
For it to work as you'd expect, 2 conditions must be satisfied:
1) the requested width is consistent with all constraits (ex. parent's width) and
2) a layout cycle is triggered.
WidthRequest: https://developer.xamarin.com/api/property/Xamarin.Forms.VisualElement.WidthRequest/

But that's complicated. I'd recommend just replacing the stack layout with a grid, and putting each element in a column of the desired width.
Grid Example: https://developer.xamarin.com/api/type/Xamarin.Forms.Grid/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...