Search code examples
c#wpfdatagridcurrentitem

Preview Mouse Down event returns sender with null referenced CurrentColumn when called first time


I run my application and fill datagrid with data. Then I click on some row and handle event in following way:

  private void dataGridCanTabParamList_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        var buffer = sender as DataGrid;

        if ((buffer == null) || (buffer.CurrentColumn == null) )
            return;

        SetCanPropertyDesription(buffer.CurrentColumn.Header.ToString());

    }

When I run this event first time the CurrentColumn is null, when I run this event second time clicking in exactly the same position CurrentColumn contains data. CurrentItem is also empty when clicked first time.

Why I don't see the data at first click?


Solution

  • That is because CurrentColumn and CurrentItem refer to selected Column/Item. When you first click, nothing is selected as you handle the tunneled event (so your code is executed before the DataGrid actually set the current item) . When you click for the second time, CurrentColumn and CurrentItem have already been set.