简体   繁体   English

Windows Phone ListView绑定

[英]Windows Phone ListView Binding

I am trying to create a ListView of items and to be able to delete them. 我试图创建项目的ListView并能够删除它们。 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. 我没有找到绑定ListViews的简单示例,因此我可以理解确切的概念。 Can you tell me what am i doing wrong ? 你能告诉我我在做什么错吗?

PS. PS。 myListOfItems is a list with strings. myListOfItems是带有字符串的列表。 The project is WP 8.1 WinRT. 该项目是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. 现在,从ListView中删除DataContext部分。

  • 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) 只需将ItemsSource设置为项目列表即可(注释执行MedSaved_ListView.DataContext = root的部分,然后取消注释并更改下一行)

     MedSaved_ListView.ItemsSource = root.medNames; 

Explanation - the ListView ItemsSource is collection used to generate the content of the ItemsControl. 说明-ListView ItemsSource是用于生成ItemsControl内容的集合。 You need to set it to some kind of IEnumerable. 您需要将其设置为某种IEnumerable。 Your medNames is of type List which implements IEnumerable so you need to set the ItemsSource to it. 您的medNames是实现IEnumerable的List类型,因此您需要为其设置ItemsSource。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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