有什么方法可以确定最后一个listboxitem何时进入视图?

时间:2014-03-13 16:15:30

标签: windows-phone-8 windows-phone windows-phone-7.1

我是Windows手机新手,来自ios背景。我的问题是,我如何以编程方式确定最后一个listboxitem何时进入视图?我目前正在使用自定义listboxitem并以编程方式添加每个项目。

1 个答案:

答案 0 :(得分:0)

在Windows Phone 8的大多数情况下,最好使用LongListSelector代替ListBox控件。

LongListSelector不是一次加载所有项目,而是虚拟化其内容,仅根据需要加载数据以在其视口中显示。

当为新项目分配UI容器(已实现)时,将触发ItemRealized事件。使用此事件确定您是否接近数据源中项目的末尾,然后加载更多数据。

<强> XAML

<phone:LongListSelector x:Name='longListFlights'
                        ItemsSource='{Binding}'
                        ItemRealized='longListFlights_ItemRealized'
                        Height='205'
                        Margin='20'>
  <phone:LongListSelector.ItemTemplate>
    <DataTemplate>

      <StackPanel Orientation='Horizontal'>
        <TextBlock Text='{Binding FlightNumber}'
                     Foreground='Yellow' />

        <TextBlock Text='{Binding TimeStamp}'
                     Margin='20,0,0,0' />
      </StackPanel>
    </DataTemplate>
  </phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>

<强> CODE

public partial class MainPage : PhoneApplicationPage {
    private ObservableCollection<Flight> _flights = 
                         new ObservableCollection<Flight>();
    private bool _isLoadingData;

    public MainPage() {
      InitializeComponent();

      AddFlights(60);
      this.DataContext = _flights;
    }

    private void AddFlights(int numberFlightsToAdd) {
      _isLoadingData = true;
      int max = _flights.Count + numberFlightsToAdd;
      for (int i = _flights.Count; i < max; i++)
      {
        _flights.Add(new Flight { FlightNumber = string.Format("AB-{0:D3}", i),
                                  TimeStamp = DateTime.Now });
      }
      _isLoadingData = false;
    }

    private void longListFlights_ItemRealized(object sender, 
                                              ItemRealizationEventArgs e) {

      Flight flight = e.Container.Content as Flight;
       if (flight != null)
      {
        if (!_isLoadingData)
        {
          // get current count of data-source
          int count = _flights.Count;

          // get index of item being realized (placed in container)
          int index = _flights.IndexOf(flight);

          // if we are close to the end, load more data
          if (count - index <= 5)
          {
            AddFlights(10);
          }
        }
        Console.WriteLine(flight.FlightNumber);
      }
    }
  }

  internal class Flight {

    public string FlightNumber { get; set; }
    public DateTime TimeStamp { get; set; }
  }
}

<强>截图

Screenshot