I attached event "DataGridColumnHeader_MouseRightButtonDown" on Loaded event to open context menu to display column names. It's working fine.
private void dtaGrd_Loaded(object sender, RoutedEventArgs e)
{
columnHeaders = TreeHelper.GetVisualChildCollection<DataGridColumnHeader>(this);
foreach (DataGridColumnHeader columnHeader in columnHeaders)
{
columnHeader.MouseRightButtonDown += DataGridColumnHeader_MouseRightButtonDown;
}
}
But when I uncheck column then Visibility of "Name" column to be Collapsed. Again, I checked that column to set Visibility to "Visible" then "DataGridColumnHeader_MouseRightButtonDown" event is not working.
Is my Implementation is wrong or DataGridColumnHeader will create new instance when visibility is change?
Yes, I found that when visilbity of DataGridColumnHeader is changed then it's Loaded event is also fires. So, We have to bind even handlers on loaded event of DataGridColumnHeader.
On which event of datagrid I come to know that DataGridColumnHeader is Loaded ? Or Where I have to attach DataGridColumnHeader Loaded Event ?
First, you should be known that each time you change visibility of any control, its 'Loaded' event executes.
Here in your case, you're providing handlers to the column headers of the datagrid by finding from visual collection of the DataGrid.
So, once you flip Visibility
of the column from Visible
to Collapsed
it'll unload column from datagrid and again, when you make it Visible
it loads with default style provided to the header.
And here comes the main problem that handlers you binded to the column Header will not be found as column got Reset
My opinion is to give try to Custom Commands or you've to manage attaching/detaching handlers while fliping visibility.
Thanks :)