Monday, April 28, 2014

WPF DataGrid RowDetails eats the first click.

I have this problem where I have a panel of buttons inside my DataGrid's RowDetails. When I first open the window , I see RowDetails of the first row shown as expected but not selected.

The symptoms : when I click on one of the buttons inside my current row's RowDetails , the DataGrid eats up the click and focuses the row instead of executing the click of the button. The second time I click on the button it works.

The complicated explanation: when you click on any button there is an algorithm that gets executed before determining that this operation is a successful click or not. This the highlights of the algorithm.
1- if mouse down is received on the button
2-   mouse is captured
3-   a set of flags are set to track the operation
4- when the mouse is up
5-   the flags need to be set.
6-   the most important mouse status should be Captured

now this contradicts/conflicts with some of RowDetails' implementation.  Which attempts to set the RowDetails' beholder row to selected.  Before doing this , it checks if the current row equals the RowDetails' beholding row. But the problem is that it is doing it the wrong way. It checks the CurrentItem instead of checking the SelectedItem.

So the simplest solution I came up with , is to sync SelectedItem with CurrentItem as follows:
       
        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);

            // to stop RowDetails from eating the first click.
            if (e.Property.Name == "SelectedItem" && CurrentItem == null) CurrentItem = SelectedItem;
        }

and no IsSynchronizedWithCurrentItem did not help resolving the problem.