在Xamarin Forms中使用XAML显示带分隔符的字符串数组
本文关键字:分隔符 字符串 数组 显示 XAML Forms Xamarin | 更新日期: 2023-09-27 18:02:39
我想打印一个字符串数组,每个字符串之间有一个分隔符示例代码块
string[] array;
string[] assignment = {"world","testing","array","hello"};
for(int i =0 ; i>assignment.Length; i++)
{
array[i] = assignment[i];
}
XAML
<controls:TappableCustomFontLabel
x:Name="array"
Text="{Binding array}"
XAlign="Start"
LineHeight="2.1"/>
XAML.CS
array.fillX();
我想将数组中的每个字符串显示在一个单独的标签上,后面跟着一个分隔符即
世界测试
数组
你好
使用ListView
或CollectionView
,并将ItemsSource
设置为string[]
数组。您可以在View或ViewModel中定义string[]
数组。建议在ViewModel中定义数组。
请注意,较大的数组,列表或集合在View.cs (Code behind)有性能问题。视图中定义的较大集合使得滚动ListView
或CollectionView
变得粗糙和不均匀。因此,在滚动较大的ListView
或CollectionView
时,滚动会延迟。因此,在ViewModel中定义数组、列表和集合。
如果你只使用View.cs
public string[] Fruits
{
get { return new string[] { "Mango", "Apple", "Pineapple", "Grapes", "Orange" }; }
}
public ListDemoPage // Page Constructor
{
InitializeComponent();
BindingContext = this;
}
或者如果您正在使用ViewModel:(如果您不使用ViewModel则跳过此)
public class ListDemoPageViewModel : INotifyPropertyChanged
{
public string[] Fruits
{
get { return fruits; }
set { fruits = value; OnPropertyChanged(nameof(Fruits)); }
}
string[] fruits;
public ListDemoPageViewModel() // ViewModel Constructor
{
Fruits = new string[] { "Mango", "Apple", "Pineapple", "Grapes", "Orange" }; }
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
仅当你使用ViewModel时,将绑定上下文设置为View.cs中的ViewModel类的实例:(如果你不使用ViewModel则跳过此)
ListDemoPageViewModel listDemoPageViewModel = new ListDemoPageViewModel();
public ListDemoPage // Page Constructor
{
InitializeComponent();
// set your Binding Context to instance of ViewModel class
BindingContext = listDemoPageViewModel;
}
最后在XAML
<ListView ItemsSource="{Binding Fruits}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding .}" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<!-- OR You can use CollectionView -->
<CollectionView ItemsSource="{Binding Fruits}">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Frame BorderColor="Gray" Margin="5">
<Label Text="{Binding .}" />
</Frame>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>