这篇博客讲到了很重要的Listbox数据绑定问题,简单的来分析下:
首先是XAML:
<phone:PhoneApplicationPage
x:Class="JsonExample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<Grid>
<ListBox x:Name="Lst">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Path=BookName}" Margin="70 10" FontSize="18"></TextBlock>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</phone:PhoneApplicationPage>
ListBox中通过DataTemplate设置了项,然后Binding Path指定了绑定的属性,在查找绑定对象的时候,系统会沿着UI树从下往上查找名为BookName的属性,具体就不在这里多说了。
下面是CS代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using JsonExample.Resources;
using System.Collections.ObjectModel;
using System.IO;
namespace JsonExample
{
public partial class MainPage : PhoneApplicationPage
{
private ObservableCollection<BookInfo> books ;
// 构造函数
public MainPage()
{
InitializeComponent();
books = new ObservableCollection<BookInfo>();
Lst.ItemsSource = books;
books.Add(new BookInfo("sss", "ee"));
books.Add(new BookInfo("sss", "宿舍"));
}
}
}
这是结果图,ADD的两项都显示了。
最后贴上简单的类的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JsonExample
{
/// <summary>
/// 存储每一项的消息
/// </summary>
public class BookInfo
{
public String BookId { get; set; }
public String BookName { get; set; }
public BookInfo(String i, String n)
{
BookId = i;
BookName = n;
}
}
}