這篇博客講到了很重要的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;
}
}
}