了解 WidthRequest [英] Understanding WidthRequest
问题描述
我想更改 WidthRequest
.因此我注意到这并没有真正设置元素的 width.而是一种提议.
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.
示例:我有一个 ListView
作为子项添加到 StackLayout
.我正在为 ListView
设置一个 WidthRequest
,但结果不是我所期望的.
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,
},
};
这是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.但在这里我得到了整个列表视图的最小宽度.
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.
如果我将 WidthRequest
设置为 60 或 120,则没有区别.结果宽度相同(而不是我想要的宽度).
There is no difference if I set WidthRequest
to 60 or 120. The resulting width is the same (and not what I want).
WidthRequest
在这里如何工作?我是否必须更改一些 LayoutOptions
?
How does WidthRequest
work here? Do I have to change some LayoutOptions
?
推荐答案
WidthRequest 只是描述了在下一个布局周期中元素所需的宽度.
要使其按预期工作,必须满足 2 个条件:
1) 请求的宽度与所有约束(例如父级的宽度)和
一致2)触发一个布局周期.
宽度请求:https://developer.xamarin.com/api/property/Xamarin.Forms.VisualElement.WidthRequest/
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/
但这很复杂.我建议只用网格替换堆栈布局,并将每个元素放在所需宽度的列中.
网格示例:https://developer.xamarin.com/api/type/Xamarin.Forms.Grid/
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/
这篇关于了解 WidthRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!