Windows Phone 8.1 数据绑定ListView [XAML]

Windows Phone 8.1 Data Binding ListView [XAML]

C#:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();

            this.NavigationCacheMode = NavigationCacheMode.Required;
        }

        public class data
        {
            public string id { get; set; }
        }

        List<data> datalist = new List<data>();

        int counter = 100000000;

        private void button_Click(object sender, RoutedEventArgs e)
        {
            data add = new data();
            counter += 1;
            add.id = counter.ToString();
            datalist.Add(add);
        }
    }

XAML :

<Page
    x:Class="SocialApp1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SocialApp1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <Button x:Name="button" 
                Content="Get" HorizontalAlignment="Left" Margin="67,550,0,0" VerticalAlignment="Top" Click="button_Click" Width="368"/>
        <ListView Margin="24,0,19,311">
            <ListView.ItemTemplate>
              <DataTemplate>
                <Border CornerRadius="20" Background="DodgerBlue" Height="65">
                  <StackPanel Orientation="Horizontal">
                    <TextBlock TextWrapping="Wrap" Margin="10" Text="{Binding id}" FontSize="20" />
                  </StackPanel>
                </Border>
              </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Page>

嗨,我一直在尝试在 windows phone 8.1 中进行数据绑定。我 post 所有代码以防万一我遗漏了什么。我如何让它工作?因为当我将它部署到我的 phone 上并按下 Get 按钮时,它什么也没做。

期望的输出:

1) 每次用户按下 Get 按钮时增加 id

2) 在datalist中添加新的id

3) 将其呈现在 ListView 中。

要更新 ListView 中的项目,必须通知绑定 属性 已更改。在这种情况下,您有要向其添加项目的集合,但不会通知 ListView 集合已更改。要通知 ListView 集合已更改,您必须使用从中派生的 ObservableCollection<T> 或 class。这意味着您必须将 List<data> 更改为 ObservableCollection<data>

ObservableCollection<data> dataList { get; set; }

如果您想将自定义 methods/properties 添加到集合中或更容易通过 XAML 声明实例,您可能需要创建 ObservableCollection<T> 的子class以避免以后重构。为什么你可能想要创建一个 subclass 而不是直接使用 ObservableCollection<T> 在这个问题的答案中解释:Collection that inherits from ObservableCollection - What are the benefits?

如果您以后 运行 遇到类似的问题,例如当集合的项目更改时 ListView 没有更改,您应该查看 INotifyPropertyChanged 界面。