WPF:数据模板

WPF:DataTemplate

在XAML界面当中编写的任何代码, 其实本质上都是转化成C#代码, 既然如此来说, 只要XAML有的对象,我们都可以用C#代码编写, 但是为什么一般我们不这么做, 是因为XAML更加容易去表达界面上的元素, 代码的可视化以及可维护性。

需求:当我想要在ListBox或者DataGridView中生成许多行时,并且每一行的内容都不一样。

我们都会想到在后台代码中创建一个类,然后设置ListBox或者DataGridView的ItemSource就行,这时会发现所绑定的集合都是一样的数据,也就是xaml中数据模板中初始设置的数据。

采用DataBinding后,就可以避免这样,xaml中的代码如下:

 <Grid>
     <Grid.RowDefinitions>
         <RowDefinition />
         <RowDefinition />
     </Grid.RowDefinitions>
     <StackPanel Margin="10" Orientation="Vertical">
         <ListBox x:Name="list">
             <ListBox.ItemTemplate>
                 <DataTemplate>
                     <StackPanel Orientation="Horizontal">
                         <Border Width="10" Height="10" Background="{Binding Code}" />
                         <TextBlock Margin="10,0" Text="{Binding Name}" />
                     </StackPanel>
                 </DataTemplate>
             </ListBox.ItemTemplate>
         </ListBox>
     </StackPanel>
     <StackPanel Grid.Row="1" Margin="10">
         <DataGrid x:Name="dataGrid" AutoGenerateColumns="False" CanUserAddRows="False" >
             <DataGrid.Columns>
                 <DataGridTextColumn Header="Code" Binding="{Binding Code}" />
                 <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                 <DataGridTemplateColumn Header="Action">
                     <DataGridTemplateColumn.CellTemplate>
                         <DataTemplate>
                             <StackPanel Orientation="Horizontal">
                                 <Button Content="Edit" />
                                 <Button Content="Delete" />
                                 <Button Content="View" />
                             </StackPanel>
                         </DataTemplate>
                     </DataGridTemplateColumn.CellTemplate>
                 </DataGridTemplateColumn>
             </DataGrid.Columns>
         </DataGrid>
     </StackPanel>
 </Grid>

注意:该代码在dataGridView最后一列中套了一个数据模板,包括了三个横向排列发按钮。

后台代码如下:

 public partial class MainWindow : Window
 {
     public MainWindow()
     {
         InitializeComponent();
         List<Color> colors = new List<Color>();
         colors.Add(new Color { Code = "#FFb6C1", Name = "浅粉红" });
         colors.Add(new Color { Code = "#FFC0CB", Name = "粉红" });
         colors.Add(new Color { Code = "#FFD700", Name = "紫色" });
         colors.Add(new Color { Code = "#FF1493", Name = "深红" });
         list.ItemsSource = colors;
         dataGrid.ItemsSource = colors;
     }
 }
 public class Color
 {
     public string Code { get; set; }
     public string Name { get; set; }
 }

最后结果如下:

image-20240820213325918

从代码看出,整个显示的过程是由数据驱动而来,完全脱离了Winform中的事件驱动,在xaml中只需要绑定即可。

posted @ 2024-08-20 21:41  追忆呢  阅读(45)  评论(0编辑  收藏  举报