数据模板 DataTemplate
<Grid> <ListBox x:Name="list"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <Border Width="10" Height="10" Background="{Binding Code}"/> <TextBlock Text="{Binding Name}" Margin="10,0"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid>
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); List<MyColor> myColors = new List<MyColor>(); myColors.Add(new MyColor { Code = "Red", Name = "红色" }); myColors.Add(new MyColor { Code = "Green", Name = "绿色" }); myColors.Add(new MyColor { Code = "Blue", Name = "蓝色" }); list.ItemsSource= myColors; } } public class MyColor { public string Code { get; set; } public string Name { get; set; } }
DataGrid 模板例子
<Grid> <DataGrid x:Name="grid" AutoGenerateColumns="False" CanUserAddRows="False"> <DataGrid.Columns> <DataGridTextColumn Header="Code" Binding="{Binding Code}"/> <DataGridTextColumn Header="Name" Binding="{Binding Name}"/> <DataGridTemplateColumn Header="操作"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <Button Content="编辑"/> <Button Content="删除" Margin="10,0"/> </StackPanel> <!--<StackPanel Orientation="Horizontal"> <Border Width="10" Height="10" Background="{Binding Code}"/> <TextBlock Text="{Binding Name}" Margin="10,0"/> </StackPanel>--> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> </Grid>
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); List<MyColor> myColors = new List<MyColor>(); myColors.Add(new MyColor { Code = "Red", Name = "红色" }); myColors.Add(new MyColor { Code = "Green", Name = "绿色" }); myColors.Add(new MyColor { Code = "Blue", Name = "蓝色" }); grid.ItemsSource= myColors; } } public class MyColor { public string Code { get; set; } public string Name { get; set; } }