DataGrid.AutoGenerateColumns 属性

定义

获取或设置一个值,该值指示是否自动创建列。

public:
 property bool AutoGenerateColumns { bool get(); void set(bool value); };
public bool AutoGenerateColumns { get; set; }
member this.AutoGenerateColumns : bool with get, set
Public Property AutoGenerateColumns As Boolean

属性值

如果自动创建列,则为 true;否则为 false。 已注册的默认值为 true。 有关可以影响值的因素的更多信息,请参见 DependencyProperty

示例

以下示例演示如何在 事件处理程序中创建 AutoGeneratingColumn 列并在创建时更改列。

<!-- The DataGrid.DataContext is a DataTable that contains a list of customers.  The DataTable columns are  
     Title, FirstName, MiddleName, LastName, Suffix, CompanyName, EmailAddress, and Phone.-->
<DataGrid Name="DG1" ItemsSource="{Binding}" AutoGenerateColumns="True" AutoGeneratingColumn="DG1_AutoGeneratingColumn" />
//Access and update columns during autogeneration
private void DG1_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    string headername = e.Column.Header.ToString();

    //Cancel the column you don't want to generate
    if (headername == "MiddleName")
    {
        e.Cancel = true;
    }

    //update column details when generating
    if (headername == "FirstName")
    {
        e.Column.Header = "First Name";
    }
    else if (headername == "LastName")
    {
        e.Column.Header = "Last Name";
    }
    else if (headername == "EmailAddress")
    {
        e.Column.Header = "Email";
    }
}
'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 = "MiddleName" Then
        e.Cancel = True
    End If

    'update column details when generating
    If headername = "FirstName" Then
        e.Column.Header = "First Name"
    ElseIf headername = "LastName" Then
        e.Column.Header = "Last Name"
    ElseIf headername = "EmailAddress" Then
        e.Column.Header = "Email"
    End If
End Sub

注解

将 设置为 AutoGenerateColumnstruefalse 将创建或删除自动生成的列。 当 属性 AutoGenerateColumns 设置为 true时, AutoGeneratingColumn 将为创建的每个列引发 事件。 可以更改或取消在事件处理程序中创建的 AutoGeneratingColumn 列。

完成所有列的自动生成后,将 AutoGeneratedColumns 引发 事件。

注意

DataGrid 当源为 XML 数据时,无法自动生成列。 在本例中,请创建自定义 Columns 集合。 有关示例,请参见 DataGridTextColumn

适用于

另请参阅