Change DataGrid column header text

后端 未结 6 861
说谎
说谎 2021-01-11 23:26

I have a list of a specific class type Person and I want to make a DataGrid with it.

private void DataGrid_Loaded(object sender, Ro         


        
相关标签:
6条回答
  • 2021-01-11 23:59
    myDataGrid.Columns[0].Header="First Name";    
    myDataGrid.Columns[1].Header="Last Name";
    

    all them work for me but you have to put code after datagrid loaded

    0 讨论(0)
  • 2021-01-12 00:01

    you can set :

     myDataGrid.Columns[0].Header="First Name";
     myDataGrid.Columns[1].Header="Last Name";
    
    0 讨论(0)
  • 2021-01-12 00:01

    Try this,

    (sender as DataGrid).Columns[0].Header="First Name";
    (sender as DataGrid).Columns[1].Header="Last Name";
    
    0 讨论(0)
  • 2021-01-12 00:02

    if you use sql for getting data, I mean don't use entity framework you can use an Alias for your columns.

    0 讨论(0)
  • 2021-01-12 00:07

    Here the Right way to do it :

    First Define an ObservableCollection in the codebehind that will hold a list of persons

    Second Bind that list to the DataGrid ItemSource and Bind its properties

    You can change what name to display on each column by simply disabling the AutoGenerateColumns and setting their names by your self

    here the full code

    <DataGrid ItemsSource="{Binding ListPersons}" AutoGenerateColumns="False">
          <DataGrid.Columns >
                <DataGridTextColumn Header="First Name" Binding="{Binding FName}"></DataGridTextColumn>
                <DataGridTextColumn Header="Last Name" Binding="{Binding LName}"></DataGridTextColumn>
          </DataGrid.Columns>
      </DataGrid>
    

    and the code behind :

    public class Person
    {
        public String FName { get; set; }   
        public String LName { get; set; }   
    
    }
    public partial class MainWindow : Window
    {
        public ObservableCollection<Person> ListPersons { get; set; }
        public MainWindow()
        {
            ListPersons=new ObservableCollection<Person>()
            {
                new Person()
                {
                    FName = "FName1",
                    LName = "LName1"
                },
                 new Person()
                {
                    FName = "FName2",
                    LName = "LName2"
                }
    
            };
            this.DataContext = this;
    
        }
    
    
    }
    
    0 讨论(0)
  • 2021-01-12 00:09

    Try HeaderText instead of Header like this :

      myDataGrid.Columns[0].HeaderText="First Name";
      myDataGrid.Columns[1].HeaderText="Last Name";
    
    0 讨论(0)
提交回复
热议问题