Hi @杨岑 ,
Welcome to Microsoft Q&A!
It is recommended to set AutoGenerateColumns="True"
, you can refer to this document How to: Customize Auto-Generated Columns in the DataGrid Control.
Here is my test code for your reference.
<Grid>
<controls:DataGrid Height="600" Margin="12"
AutoGenerateColumns="True" AutoGeneratingColumn="DataGrid_AutoGeneratingColumn" ItemsSource="{x:Bind Persons}" />
</Grid>
public sealed partial class MainPage : Page
{
public List<Person> Persons { get; set; }
public MainPage()
{
this.InitializeComponent();
Persons = new List<Person>
{
new Person
{
PersonId = 1, IsChecked = true, FirstName = "Ronald", LastName = "Rumple",
Position = "Network Administrator"
},
new Person
{
PersonId = 2, IsChecked = false, FirstName = "Brett", LastName = "Banner",
Position = "Software Developer"
},
new Person
{
PersonId = 3, IsChecked = true, FirstName = "Alice", LastName = "Anderson",
Position = "Accountant"
}
};
}
private void DataGrid_AutoGeneratingColumn(object sender, Microsoft.Toolkit.Uwp.UI.Controls.DataGridAutoGeneratingColumnEventArgs e)
{
//Modify the header of the "Name" column
if (e.Column.Header.ToString() == "PersonId")
{
e.Column.Header = "ID";
}
if (e.Column.Header.ToString() == "IsChecked")
{
e.Column.Header = "Checked";
}
}
}
public class Person
{
public int PersonId { get; set; }
public bool IsChecked { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Position { get; set; }
}
Thank you.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.