Unable to find DataGridColumn name

I found the Columns collection in my datagrid and was hoping to iterate over it to find a specific column name. However, I cannot figure out how to access the x: Name attribute of a column. This xaml illustrates my problem with DataGridTextColumn and DataGridTemplateColumn:

<t:DataGrid x:Name="dgEmployees" ItemsSource="{Binding Employees}" 
    AutoGenerateColumns="false" Height="300" >
    <t:DataGrid.Columns>
        <t:DataGridTextColumn x:Name="FirstName" Header="FirstName"
Binding="{Binding FirstName}" />
        <t:DataGridTemplateColumn x:Name="LastName" Header="LastName" >
            <t:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding LastName}" />
                </DataTemplate>
            </t:DataGridTemplateColumn.CellTemplate>
        </t:DataGridTemplateColumn>
    </t:DataGrid.Columns>
</t:DataGrid>

And here is my code:

    DataGrid dg = this.dgEmployees;
    foreach (var column in dg.Columns) 
    {
        System.Console.WriteLine("name: " + (string)column.GetValue(NameProperty));
    }

There is no value at run time; column.GetValue returns nothing. Using Snoop, I confirmed that there is no Name property in the DataGridTextColumn or DataGridTemplateColumn.

What am I missing?

+3
source share
2 answers

WPF , : x: Name, , , XAML, .. XAML FrameworkElement.Name, .

FrameworkElement.Name, x: Name , XAML. , non FrameworkElement , , .

:

WPF, x: Name Name?

, . :

public class DataGridUtil
{

    public static string GetName(DependencyObject obj)
    {
        return (string)obj.GetValue(NameProperty);
    }

    public static void SetName(DependencyObject obj, string value)
    {
        obj.SetValue(NameProperty, value);
    }

    public static readonly DependencyProperty NameProperty =
        DependencyProperty.RegisterAttached("Name", typeof(string), typeof(DataGridUtil), new UIPropertyMetadata(""));

}

...

xmlns:util="clr-namespace:WPFDataGridExamples"

<t:DataGrid x:Name="dgEmployees" ItemsSource="{Binding Employees}" 
    AutoGenerateColumns="false" Height="300" >
    <t:DataGrid.Columns>
        <t:DataGridTextColumn util:DataGridUtil.Name="FirstName" Header="FirstName"
Binding="{Binding FirstName}" />
        <t:DataGridTemplateColumn util:DataGridUtil.Name="LastName" Header="LastName" >
            <t:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding LastName}" />
                </DataTemplate>
            </t:DataGridTemplateColumn.CellTemplate>
        </t:DataGridTemplateColumn>
    </t:DataGrid.Columns>
</t:DataGrid>

:

DataGrid dg = this.dgEmployees;
foreach (var column in dg.Columns) 
{
    System.Console.WriteLine("name: " + DataGridUtil.GetName(column));
}

,

+11

linq datagrid

dgvReports.Columns.Select(a=>a.Header.ToString()).ToList()

dgvReports - datagrid.

+1

Source: https://habr.com/ru/post/1783296/


All Articles