views:

186

answers:

2

I use a datagrid with a checkboxcolumn in c# 4.0. I right now I need 2 clicks to change the state of a checkbox if I enable row selection.

One click selects the row and the second changes the state of the checkbox. How can I enable row selection, but keep the 1 click for changing the state of the checkboxcolumn?

        <DataGrid AutoGenerateColumns="False"
               SelectionMode="Single"   SelectionUnit="CellOrRowHeader"
              ItemsSource="{Binding}" 

              Height="200" HorizontalAlignment="Left" Margin="28,43,0,0"
              Name="gridPersons" VerticalAlignment="Top" Width="292" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Width="SizeToCells"   MinWidth="150"
                                       Binding="{Binding Name}" 
                                       IsReadOnly="True"/>
            <DataGridCheckBoxColumn Header="Selected" Width="SizeToCells"   MinWidth="100"
                                       Binding="{Binding IsSelected}"  
                                       IsReadOnly="false"/>


        </DataGrid.Columns>


    </DataGrid>
A: 

ok, since nobody wants to provide a good answer for this :) here's a trick\hack which should be doing what you need:

add an SelectedCellsChanged event handler to your grid:

SelectedCellsChanged="gridPersons_SelectedCellsChanged"

below is the code for the event handler which would put the selected cell into the editing mode and simulate an additional mouse click on it which would switch the check box.

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);

private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;

[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
    public int X;
    public int Y;
}

[DllImport("user32.dll")]
static extern uint GetCursorPos(out POINT lpPoint);    

private void gridPersons_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
    // check here if this is the cell with a check box

    gridPersons.BeginEdit();

    POINT point;
    GetCursorPos(out point);
    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, point.X, point.Y, 0, 0);
}

hope this helps, regards

serge_gubenko
+1  A: 

Hi,

have a look at the accepted answer of this question - it uses a DataTemplateColumn with a standard CheckBox instead of the CheckBoxColumn. That gives you single click editing and it also works if you have row selection enabled. HTH.

andyp
I think you mean a CheckBox, not a ComboBox. But I recommend also this way.
HCL
You're absolutely right, thanks. I edited the answer.
andyp