WPF基础入门
Class3: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" });//数据绑定到listlist.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中穿插控件操作--><BorderWidth="10"Height="10"Background="{Binding Code}"></Border><TextBlock Margin="10, 0" Text="{Binding Name}"></TextBlock></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox>
</Grid>
3、效果: