当前位置:网站首页>WPF DataGrid using data templates

WPF DataGrid using data templates

2022-08-10 01:28:00 flysh05

1. 创建数据模型类

public class TestPointModel
{
    
        public int Id {
     get; set; }
        public string TestPointName {
     get; set; }
        public DateTime TestDateTime {
     get; set; }
        public string Details
        {
    
            get
            {
    
                return $"{
      Id} ,{
      TestPointName} have tested on {
      TestDateTime}";
            }
        }
    }

2. UI设计

<DataGrid x:Name="dgTestPoints" Margin="5" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID" Binding="{Binding Id}" Width="50"/>
                <DataGridTextColumn Header="PointName" Binding="{Binding TestPointName}" Width="120"/>
                <DataGridTextColumn Header="DateTime" Binding="{Binding TestDateTime}" Width="200"/>
            </DataGrid.Columns>

            <!-- Visibility 属性 Visible,Collapsed,Hidden -->
            <DataGrid.RowDetailsTemplate>
                <DataTemplate>
                    <TextBlock Margin=" 10" Visibility="Visible" Text="{Binding Details}"></TextBlock>
               </DataTemplate>
            </DataGrid.RowDetailsTemplate>
        </DataGrid>

Create a data source using data model classes,所以AutoGenerateColumns=“False”

使用DataGridTextColumn Binding model's property fields.

3.UI 后台代码

public MainWindow()
{
    
      InitializeComponent();
      dgTestPoints.ItemsSource = CreatDataSource();
 }

  

 //Create Data sorce for DataGrid Control show
private static List<TestPointModel> CreatDataSource()
{
    

   List<TestPointModel> testPoints = new List<TestPointModel>();
   testPoints.Add(new TestPointModel() {
     Id = 1, TestPointName = "VoltageTest", TestDateTime = new DateTime(2022, 7, 23) });
   testPoints.Add(new TestPointModel() {
     Id = 2, TestPointName = "CurrentTest", TestDateTime = new DateTime(2022, 1, 17) });
  testPoints.Add(new TestPointModel() {
     Id = 3, TestPointName = "SwitchTest", TestDateTime = new DateTime(2022, 9, 2) });

    return testPoints;
}

Create a data collection for the data model,绑定到DataGrid 的ItemsSource 属性.

显示效果如下:

原网站

版权声明
本文为[flysh05]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208092312550636.html