问题描述
我想更改 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仅描述下一个布局周期中元素的所需宽度.
为了使其按预期工作,必须满足两个条件:
1)请求的宽度与所有要素(例如,父母的宽度)和
2)触发布局周期.
WidthRequest: 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!