How to populate LongListSelector

前端 未结 1 841
名媛妹妹
名媛妹妹 2020-12-06 08:33

I\'m starting out with C# Windows Phone 8 development and I am trying to write an app which uses a LongListSelector. The app will show a long list of train station names.

相关标签:
1条回答
  • 2020-12-06 08:50

    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.

    0 讨论(0)
提交回复
热议问题