简体   繁体   中英

Windows Phone ListView Binding

I am trying to create a ListView of items and to be able to delete them. Here is my code. I can't get the list of items to display. I didn't find a simple example of binding ListViews so i can understand the exact concept. Can you tell me what am i doing wrong ?

PS. myListOfItems is a list with strings. The project is WP 8.1 WinRT.

    public class MedClass
    {
        public string medName { get; set; }
    }

    public class MedClassRoot
    {
        public List<MedClass> medNames { get; set; }
    }

    public sealed partial class MedSavedPage : Page
    {
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            MedClassRoot root = new MedClassRoot();
            root.medNames = new List<MedClass>();

            foreach (var element in myListOfItems)
            {
                root.medNames.Add(new MedClass {medName = element});
            }

            MedSaved_ListView.DataContext = root;
            //MedSaved_ListView.ItemsSource = root;
        }

    <ListView DataContext="{Binding root}"
              x:Name="MedSaved_ListView" 
              HorizontalAlignment="Left" 
              Height="507" 
              Margin="10,73,0,0" 
              VerticalAlignment="Top" 
              Width="380" Tapped="MedSaved_ListView_Tapped">

        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Height="30">
                    <TextBlock Text="{Binding medName}" FontSize="16"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

This is the quickest way to get it to work:

  • Remove the DataContext part from the ListView for now.

  • Simply set the ItemsSource to the list of your items (comment the part where you do MedSaved_ListView.DataContext = root, and uncomment and alter the next line)

     MedSaved_ListView.ItemsSource = root.medNames; 

Explanation - the ListView ItemsSource is collection used to generate the content of the ItemsControl. You need to set it to some kind of IEnumerable. Your medNames is of type List which implements IEnumerable so you need to set the ItemsSource to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM