Windows Phone ListView Binding

怎甘沉沦 提交于 2020-01-17 08:09:18

问题


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>

回答1:


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.



来源:https://stackoverflow.com/questions/28646058/windows-phone-listview-binding

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