C# WPF 如何在代码隐藏中按比例调整数据网格列的大小

C# WPF how to resize datagrid columns proportionally in code behind

我有一个数据网格,其列属性必须在后面的代码中以编程方式更改,为此我使用事件

AutoGeneratingColumn="Datagrid_AutoGeneratingColumn"

我做的:

 private void Datagrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
  string strDatagridName = (sender as DataGrid).Name;
  switch (strDatagridName.ToUpper())
  {
    case "DTGPPTAB1":
    case "DTGPPTAB3":
      switch (e.PropertyName.ToUpper())
      {
        /*----Visible ----*/
        case "DESCRIPTION": e.Column.Header = Langs.Word(Langs.eWords.Description); e.Column.Width = 33; break;<-------------here
        case "NOTE": e.Column.Header = Langs.Word(Langs.eWords.Notes);  break;
        case "PARTPROGRAMFILENAME": e.Column.Header = Langs.Word(Langs.eWords.PPfilename);  break;

          /*----Hidden ----*/
        case "LSTBLADES": e.Column.Header = Langs.Word(Langs.eWords.Blades); break;
        case "LSTMYIMAGES": e.Column.Header = Langs.Word(Langs.eWords.Image); e.Column.Visibility = Visibility.Collapsed;  break;
        case "LSTMYSOUNDFILES": e.Column.Header = Langs.Word(Langs.eWords.Sound); e.Column.Visibility = Visibility.Collapsed; break;
        case "BARCODE": e.Column.Header = Langs.Word(Langs.eWords.Barcode); e.Column.Visibility = Visibility.Collapsed; break;
        case "PROGRAMTRACEFIELDS": e.Column.Header = Langs.Word(Langs.eWords.ProgramTracefields); e.Column.Visibility = Visibility.Collapsed; break;
        default: e.Column.Header = e.PropertyName; break;
      }
      break;
  }

一切正常。 我需要的是 DESCRIPTION 案例。在这里我可以以像素为单位设置列宽,但我无法按比例设置它,例如33%.

所以简而言之,我想设置前 3 列以将整个数据网格 space 分成 33% 33% 33%。所以以 % 而不是以像素为单位。 谢谢

您需要将 Width 设置为 double,而不是将其设置为 DataGridLength。这是一个例子:

e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);

将这些列设置为 1* 应该足以公平分配宽度(3 列为 33%)。