views:

1402

answers:

2

Does anyone know if it's possible to access a DataGrid column by using it's x:name (as defined in the xaml) from within the code behind ?

I know I can use the following code :

myDataGridList.Columns[0].Header = "Some Data";

..but I would prefer to use something like this if possible:

myDataGridList.Columns["ColumnName"].Header = "Some Data";

Thanks in advance.

+5  A: 

You can extend ObservableCollection with some Linq or a foreach loop to do a linear search on the columns.

public static class MyExtensions
{
    public static DataGridColumn GetByName(this ObservableCollection<DataGridColumn> col, string name)
    {
        return col.SingleOrDefault(p =>
            (string)p.GetValue(FrameworkElement.NameProperty) == name
        );
    }
}

Then, you can call this instead of the Columns property:

myGrid.Columns.GetByName("theName");
BC
Thanks very much - works perfectly.
cyberbobcat
Nice answer. I'm finding LINQ helpful in so many places...
Erik Mork
A: 

Awesome. Thank you very much