Windows Phone 8.1数据绑定ListView [XAML]
本文关键字:XAML ListView 数据绑定 Phone Windows | 更新日期: 2023-09-27 18:08:28
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。我发布了所有的代码,以防我错过了什么。我怎么让它工作?因为当我在手机上部署它时,当我按下Get
按钮时,它什么也不做。
期望输出:
1)每次用户按下Get
按钮,增加id
。
2)在datalist
中添加新的id
。
要更新ListView中的项,必须通知绑定属性已经更改。在这种情况下,您有一个正在向其中添加项目的集合,但是ListView没有收到集合更改的通知。要通知ListView集合已经更改,您必须使用ObservableCollection<T>
或从它派生的类。这意味着您必须将List<data>
更改为ObservableCollection<data>
ObservableCollection<data> dataList { get; set; }
如果你想在集合中添加自定义方法/属性,或者通过XAML更容易地声明实例,你可能想创建ObservableCollection<T>
的子类,以避免以后的重构。为什么您可能想要创建一个子类而不是直接使用ObservableCollection<T>
,在这个问题的答案中解释了:从ObservableCollection继承的集合-有什么好处?
如果您以后遇到类似的问题,例如,当集合的项被更改时,ListView没有改变,您应该查看INotifyPropertyChanged-interface