我试图在Xamarin Forms中使用ListView,我有一个List,我必须根据当天划分它
var activitiesServices = new ActivitiesServices();
var activities = activitiesServices.GetActivities();
var dataTemplate = new DataTemplate(typeof(TextCell));
dataTemplate.SetBinding(TextCell.TextProperty, "Subject");
var list = new ObservableCollection<Activity>();
var list2 = new ObservableCollection<Activity>();
var list3 = new ObservableCollection<Activity>();
var list4 = new ObservableCollection<Activity>();
var list5 = new ObservableCollection<Activity>();
foreach (Activity item in activities) {
var day = item.StartTime.DayOfWeek;
switch ((int)day) {
case 1:
list.Add(item);
break;
case 2:
list2.Add(item);
break;
case 3:
list3.Add(item);
break;
case 4:
list4.Add(item);
break;
case 5:
list5.Add(item);
break;
default:
break;
}}
直到这里顺利但是当我尝试填充主列表视图(在xaml中定义)时它会给我一个错误:
if (list.Count != 0) {
monday.ItemsSource = list;
monday.ItemTemplate = dataTemplate;
}
if (list2.Count != 0) {
tuesday.ItemsSource = list2;
tuesday.ItemTemplate = dataTemplate;
}
if (list3.Count != 0) {
wednesday.ItemsSource = list3;
wednesday.ItemTemplate = dataTemplate;
}
if (list5.Count != 0) {
friday.ItemsSource = list5;
friday.ItemTemplate = dataTemplate;
}
if (list4.Count != 0) {
thursday.ItemsSource = list4;
thursday.ItemTemplate = dataTemplate;
}
这是错误:System.NullReferenceException:对象引用未设置为对象的实例。
答案 0 :(得分:0)
您可以尝试Syncfusion
提供的列表视图在XAML中使用。这定义了组头模板
<syncfusion:SfListView x:Name="listView">
<syncfusion:SfListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout BackgroundColor="#E4E4E4">
<Label Text="{Binding Key}"
FontSize="22"
FontAttributes="Bold"
VerticalOptions="Center"
HorizontalOptions="Start"
Margin="20,0,0,0" />
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</syncfusion:SfListView.GroupHeaderTemplate>
</syncfusion:SfListView>
它支持分组,似乎适合您的情况。