本篇文章示範由 ItemTemplate屬性定義的樣板組成一個清單項目
前言
本篇文章示範由 ItemTemplate屬性定義的樣板組成一個清單項目
示範
Step1、建立一個新專案
Step2、畫面設計
以 XAML 建立項目控制項,如下圖:
產生的 XAML 程式碼如下:
<StackPanel x:Name="ContentPanel" Grid.Row="1" Orientation="Vertical" Margin="12,0,12,0">
<StackPanel Orientation="Horizontal">
<TextBlock Text="學號" FontSize="20" Margin="5,10" />
<TextBlock Text="姓名" FontSize="20" Margin="30,10" />
<TextBlock Text="生日" FontSize="20" Margin="44,10" />
</StackPanel>
<ListBox x:Name="ListBox1"
Width="450" Height="200" HorizontalAlignment="Left"
ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding StuNo}" FontSize="20" Margin="5,10" />
<TextBlock Text="{Binding StuNa}" FontSize="20" Margin="20,10" />
<TextBlock Text="{Binding BirDate}" FontSize="20" Margin="30,10" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
Step3、在 MainPage.cs 程式碼中撰寫事件處理函式:
public partial class MainPage : PhoneApplicationPage
{
public ObservableCollection<StuRec> stuRec = new ObservableCollection<StuRec>();
public MainPage()
{
InitializeComponent();
stuRec.Add(new StuRec("10014501", "王小明", new DateTime(1995, 11, 24)));
stuRec.Add(new StuRec("10014502", "劉小美", new DateTime(1995, 7, 7)));
stuRec.Add(new StuRec("10014503", "張阿偉", new DateTime(1984, 9, 10)));
// Set the data context for the list box.
ListBox1.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();
}
}
}