WPF の基本を始める
クラス3: WPFデータテンプレート
1. まず、cs ファイルにデータを定義します。
public partial class Class_4 : Window
{
public Class_4()
{
InitializeComponent();
List<Color> test = new List<Color>();
test.Add(new Color() {
Code = "Yellow", Name = "Red" });
test.Add(new Color() {
Code = "#00FF00", Name = "Green" });
test.Add(new Color() {
Code = "#0000FF", Name = "Blue" });
//数据绑定到list
list.ItemsSource = test;
}
}
public class Color
{
public string Code {
get; set;}
public string Name {
get; set; }
}
2.xaml でテンプレートを作成する
<Grid>
<!--WPF数据模板-->
<ListBox x:Name="list">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!--通过Binding绑定了Background和Text 不用再业务代码cs中穿插控件操作-->
<Border
Width="10"
Height="10"
Background="{Binding Code}"></Border>
<TextBlock Margin="10, 0" Text="{Binding Name}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
3. 効果: