在前一篇文章示範如何綁定一個紀錄,本篇要示範如何綁定到一個紀錄集合。
前言
在前一篇文章示範如何綁定一個紀錄,本篇要示範如何綁定到一個紀錄集合。
示範
Step1、建立一個新專案
Step2、畫面設計
以 XAML 建立項目控制項,如下圖:
產生的 XAML 程式碼如下:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="lb1" ItemsSource="{Binding}" Margin="10"/>
</Grid>
Step3、在 MainPage.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 PhoneApp6.Resources;
using System.Collections.ObjectModel;
namespace PhoneApp6
{
public partial class MainPage : PhoneApplicationPage
{
public ObservableCollection<StuRec> stuRec = new ObservableCollection<StuRec>();
public MainPage()
{
InitializeComponent();
stuRec.Add(new StuRec("10014501", "王阿一", new DateTime(1992, 2, 2)));
stuRec.Add(new StuRec("10014502", "王阿二", new DateTime(1992, 4, 7)));
stuRec.Add(new StuRec("10014503", "王阿三", new DateTime(1992, 9, 5)));
lb1.DataContext = stuRec;
}
public class StuRec
{
public StuRec() { }
public StuRec(string stuNo, string stuNa, DateTime birDate)
{
StuNo = stuNo;
StuNa = stuNa;
BirDate = birDate;
}
public string StuNo { get; set; }
public string StuNa { get; set; }
public DateTime BirDate { get; set; }
// 改寫ToString 方法
public override string ToString()
{
return "學號: " + StuNo + " 姓名: " + StuNa + " 的學生," + "\n" +
"生日為 " + BirDate.ToShortDateString();
}
}
}
}