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>
使用数据模型类创建数据源,所以AutoGenerateColumns="False"
使用DataGridTextColumn
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;
}
创建数据模型的数据集合,绑定到DataGrid 的ItemsSource 属性。
显示效果如下:
网友评论