ScrollTo时ListView抛出UnhandledException

时间:2016-10-14 13:52:47

标签: c# xamarin xamarin.ios uwp xamarin.uwp

我有一个像这样的ListView的简单页面

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
   x:Class="ListViewDemo.MainPage">

   <StackLayout>
      <Grid>
         <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
         </Grid.ColumnDefinitions>
         <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
         </Grid.RowDefinitions>
         <Label Text="From" />
         <DatePicker x:Name="fromPicker" Grid.Row="1" />
         <Label Text="To" Grid.Column="1" />
         <DatePicker x:Name="toPicker" Grid.Column="1" Grid.Row="1" />
      </Grid>
      <ListView>
         <ListView.ItemTemplate>
            <DataTemplate>
               <ViewCell>
                  <StackLayout>
                     <Label Text="{Binding FromDate}" />
                     <Label Text="{Binding ToDate}" />
                  </StackLayout>
               </ViewCell>
            </DataTemplate>
         </ListView.ItemTemplate>
      </ListView>
   </StackLayout>

 </ContentPage>

当日期更改时,我想滚动到最接近当前日期的事件,但是当我在UWP上使用UnhandledException时我得到ScrollTo,而iOS只是不滚动

我正在考虑使用ItemAppearing,但如果我在列表中有足够的事件,它是否值得信任?

如果我使用await Task.Delay(500)我没有获得UnhandledException,而是内容在我的屏幕上跳转。

这个问题有解决办法吗?

public void SetEvents(params CalenderEventDto[] events)
{
   var dateToScrollTo = DateTime.Now.Date;

   var scrollToEvent = events?.OrderBy(x => x.Start.Date)?.FirstOrDefault(c => c.Start.Date >= dateToScrollTo  || c.End.Date >= dateToScrollTo );

   var orderedEvents = events.GroupBy(x => x.Start.Date).OrderBy(x => x.Key);

   _calendarEvents.Clear();

   foreach (var groupedEvents in orderedEvents)
   {
      foreach (var calendarEvent in groupedEvents)
      {
         _calendarEvents.Add(calendarEvent);
      }
   }

   //await Task.Delay(450);
   Device.BeginInvokeOnMainThread(() => lstCalendar.ScrollTo(scrollToEvent, ScrollToPosition.Start, false));
}

修改
我想通了,问题出在iOS上也是

1 个答案:

答案 0 :(得分:0)

我想通了,如果我将SetEvents从构造函数移动到OnAppearing它可以正常工作