【问题标题】:Change ColumnWidth of Datagrid which is filled per Itemsource .net更改每个 Itemssource .net 填充的 Datagrid 的列宽
【发布时间】:2015-11-29 22:43:01
【问题描述】:

我有一个填充了数据表的数据网格:

Dim dataTable as new Datatable
Dim dataGrid as new DataGrid

然后我用数据填充数据表并将其显示在数据网格中。

dataGrid.ItemsSource = dataTable.DefaultView

一切都很好。

但现在我想更改一些列的宽度,例如:

datagrid.columns(0).Width = 100

-> 错误:索引超出范围异常。 -> Datagrid 中没有列。

但我可以看到它们是列。当我设置 ItemsSource 时,它​​不会自动添加列?!

感谢您的帮助!

【问题讨论】:

  • 重要:我在代码中创建了Datagrid,所以我无法解决xaml中的问题。
  • DataGrid 会自动为您生成列吗?
  • column 不是 datagrid 的属性有关如何设置宽度的信息,请参见示例 here
  • @Glen Thomas autogenerateColumns = true,当我将其更改为 false 时,我在 Datagrid 中看不到任何数据。

标签: wpf vb.net datagrid


【解决方案1】:

您可以使用DataGrid.AutoGeneratingColumn 事件来修改您的列:

'Access and update columns during autogeneration 
Private Sub DG1_AutoGeneratingColumn(ByVal sender As Object, ByVal e As DataGridAutoGeneratingColumnEventArgs)
    Dim headername As String = e.Column.Header.ToString()
    'Cancel the column you don't want to generate 
    If headername = "IDontWantThisColumn" Then
        e.Cancel = True 
    End If 

    'update column details when generating 
    If headername = "MyFirstColumn" Then
        e.Column.Width = 100 
    ElseIf headername = "MySecondColumn" Then
        e.Column.Width = 120 
    End If 
End Sub

【讨论】:

    猜你喜欢
    • 2012-07-14
    • 1970-01-01
    • 2010-10-28
    • 2021-01-04
    • 1970-01-01
    • 2014-08-17
    • 2011-04-11
    • 1970-01-01
    • 2011-02-15
    相关资源
    最近更新 更多