ListView 和 CollectionView 在 Xamarin Forms 中比所需的 space 多 space
ListView and CollectionView are taking extra space than the required space in Xamarin Forms
我有一个 string[]
数组,它使用 Label
显示项目。为此,我正在使用 ListView
。它工作正常,唯一的问题是 ListView
占用的 space 比所需的多。我也尝试过 CollectionView
但同样的问题仍然存在。
请注意我的 ListView
在 ScrollView
之下。我想在我的页面上有可滚动的内容,其中还包含一个列表。
我最初想显示只有 Label
而没有 ListView
或 CollectionView
的项目数组。
这里有2个问题
ListView
或 CollectionView
正在使用额外的 space.
- 如何在没有
ListView
或 CollectionView
的情况下显示一小部分项目?
这两个问题只有一个解决方案。使用 StackLayout
之类的布局并将其 BindableLayout.ItemsSource
设置为您的数组、列表或集合。然后定义它的ItemTemplate
.
示例代码如下:
<StackLayout BindableLayout.ItemsSource="{Binding Fruits}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Label Text="{Binding .}" />
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
在 View 或 ViewModel 中定义数组(推荐使用 ViewModel):
public string[] Fruits { get { return new string[] { "Mango", "Apple", "Orange", "Pineapple", "Grapes" }; }}
有一种更简单的方法可以实现这一点。
只使用 Label
没有任何布局。
<Label x:Name="label"/>
基本
我们可以手动添加\n
使标签多行。
string text = "";
foreach(var str in Fruits)
{
text += str + "\n";
}
label.Text = text;
自定义
要设置标签样式,我们可以使用 FormattedText
.
FormattedString text = new FormattedString();
foreach(var str in Fruits)
{
Span sp = new Span();
sp.Text = str + "\n";
sp.FontSize = 20;
sp.LineHeight = 3;
sp.TextColor = Color.Red;
text.Spans.Add(sp);
}
label.FormattedText = text;
我有一个 string[]
数组,它使用 Label
显示项目。为此,我正在使用 ListView
。它工作正常,唯一的问题是 ListView
占用的 space 比所需的多。我也尝试过 CollectionView
但同样的问题仍然存在。
请注意我的 ListView
在 ScrollView
之下。我想在我的页面上有可滚动的内容,其中还包含一个列表。
我最初想显示只有 Label
而没有 ListView
或 CollectionView
的项目数组。
这里有2个问题
ListView
或CollectionView
正在使用额外的 space.- 如何在没有
ListView
或CollectionView
的情况下显示一小部分项目?
这两个问题只有一个解决方案。使用 StackLayout
之类的布局并将其 BindableLayout.ItemsSource
设置为您的数组、列表或集合。然后定义它的ItemTemplate
.
示例代码如下:
<StackLayout BindableLayout.ItemsSource="{Binding Fruits}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Label Text="{Binding .}" />
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
在 View 或 ViewModel 中定义数组(推荐使用 ViewModel):
public string[] Fruits { get { return new string[] { "Mango", "Apple", "Orange", "Pineapple", "Grapes" }; }}
有一种更简单的方法可以实现这一点。
只使用 Label
没有任何布局。
<Label x:Name="label"/>
基本
我们可以手动添加\n
使标签多行。
string text = "";
foreach(var str in Fruits)
{
text += str + "\n";
}
label.Text = text;
自定义
要设置标签样式,我们可以使用 FormattedText
.
FormattedString text = new FormattedString();
foreach(var str in Fruits)
{
Span sp = new Span();
sp.Text = str + "\n";
sp.FontSize = 20;
sp.LineHeight = 3;
sp.TextColor = Color.Red;
text.Spans.Add(sp);
}
label.FormattedText = text;