了解WidthRequest

时间:2016-03-07 16:59:47

标签: xamarin xamarin.ios xamarin.forms

我想更改WidthRequest。因此我注意到这并没有真正设置元素的 width 。相反,它是一种提案。

实施例: 我有一个ListView作为孩子添加到StackLayout。我为WidthRequest设置ListView,但结果不符合我的预期。

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

2 个答案:

答案 0 :(得分:3)

WidthRequest仅描述元素在下一个布局周期中所需的宽度。
为了使它按照您的预期工作,必须满足2个条件:
1)请求的宽度与所有约束(例如父节点宽度)和
一致 2)触发布局循环。
WidthRequest:https://developer.xamarin.com/api/property/Xamarin.Forms.VisualElement.WidthRequest/

但这很复杂。我建议用网格替换堆栈布局,并将每个元素放在所需宽度的列中 网格示例:https://developer.xamarin.com/api/type/Xamarin.Forms.Grid/

答案 1 :(得分:1)

您需要指定Horizo​​ntalOptions,例如“ start”或“ center” 。 stackLayout的默认horizo​​ntalOptions是FillAndExpand,因此,即使您指定了宽度,像listview这样的子元素也将填充整个可用的水平区域。对于Microsoft而言,这是一个糟糕的电话,因为默认行为将忽略/覆盖宽度请求。

这是一个直观的示例:我有一个选择器,在其中将宽度请求设置为200,该宽度请求应占据水平空间的约2/3。

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

Width request ignored

如您所见,宽度请求被覆盖/忽略。然后,如果将Horizo​​ntalOptions设置为“开始” ...

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

Width request honored

宽度请求得到满足。当然,我在这里设置.xaml文件中的属性,这是我通常首选的设置,但是您也可以像这样在C#中设置Horizo​​ntalOptions

pickerRanks.HorizontalOptions = LayoutOptions.Start;