【问题标题】:Windows Phone ListView BindingWindows Phone ListView 绑定
【发布时间】:2015-02-21 12:57:10
【问题描述】:

我正在尝试创建项目的 ListView 并能够删除它们。这是我的代码。我无法获取要显示的项目列表。我没有找到绑定 ListViews 的简单示例,因此我可以理解确切的概念。你能告诉我我做错了什么吗?

PS。 myListOfItems 是一个带有字符串的列表。该项目是 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>

【问题讨论】:

    标签: c# xaml windows-runtime windows-phone-8.1 winrt-xaml


    【解决方案1】:

    这是让它工作的最快方法:

    • 暂时从 ListView 中移除 DataContext 部分。

    • 只需将 ItemsSource 设置为您的项目列表(注释您执行 MedSaved_ListView.DataContext = root 的部分,然后取消注释并更改下一行)

      MedSaved_ListView.ItemsSource = root.medNames;
      

    说明 - ListView ItemsSource 是用于生成 ItemsControl 内容的集合。您需要将其设置为某种 IEnumerable。您的 medNames 是实现 IEnumerable 的 List 类型,因此您需要将 ItemsSource 设置为它。

    【讨论】:

    • 当我想从 ListView 中删除一个元素时,我会从 medNames 中删除该元素,但是如何刷新 ListView 使其不显示该元素?
    • @Macaret 在这种情况下,您的设置有点错误。您需要使用 ObservableCollection,因为它能够在发生集合更改事件时通知 UI(例如,当您删除项目时)。请阅读有关主题的许多教程中的一些:数据绑定、ObservableCollection、ListBox 或 ListView,甚至可能是 MVVM,例如:blogs.msdn.com/b/quick_thoughts/archive/2014/06/10/…
    • 谢谢你给我的链接。我实现了 ObservableCollection 并成功显示了我的列表并删除了一个项目。
    • @Macaret 欢迎您。如果它回答了您的问题,请将其标记为“答案”,以便其他人也可以从中受益。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 2013-12-30
    • 2014-12-08
    • 1970-01-01
    相关资源
    最近更新 更多