Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access a Silverlight DataGrid Column by name rather than by column index?

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.

like image 502
cyberbobcat Avatar asked Feb 09 '09 12:02

cyberbobcat


1 Answers

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");
like image 102
BC. Avatar answered Nov 15 '22 12:11

BC.