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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With