How to populate LongListSelector

三世轮回 提交于 2019-11-27 23:21:02
Romasz

Here is a basic example which should help you understand: First in your Page (xaml file) you define the control LongListSelector (LLS):

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <phone:LongListSelector Name="myLLS" Margin="0">
        <phone:LongListSelector.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </phone:LongListSelector.ItemTemplate>
    </phone:LongListSelector>
</Grid>

You also declare how its Items will look like. It can be any UIElement - a button, Image, Grid and so on. In the code above I declared that my Item would be a TextBlock which content (text) I've bound to a property 'Name'. I've also given the LLS a name, that I can refer to it later.

In Page.cs code you populate the LLS. Lets create the simple Station class, and populate LLS:

public class Station
{
  private string _stationName;

  public string Name
  {
     get { return _stationName; }
     set { _stationName = value; }
  }

  public Station(string station)
  {
     this.Name = station;
  }
}

public partial class MainPage : PhoneApplicationPage
{
  ObservableCollection<Station> trainStations = new ObservableCollection<Station>();

  public MainPage()
  {
     InitializeComponent();

     myLLS.ItemsSource = trainStations;

     trainStations.Add(new Station("Germany"));
     trainStations.Add(new Station("France"));
     trainStations.Add(new Station("Italy"));
  }
}

What is important:

  • look that in my Station class there is property called 'Name' - that's the one to which content of the TextBlock is bound.
  • I've created ObservableCollection which is a collection of my Stations - it's similar to a List but when the new item is added or removed the PropertyChanged event is raised and therefore your LongListSelector can be automatically updated when you add a new station.
  • I've assigned created collection to myLLS.ItemsSource - it means that created LLS will be populated with Items (described in xaml as DataTemplate) and a Source of this items is that collection.

Hope this helps. Happy coding.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!