I use a DataGrid
with a CheckBoxColumn
in c# 4.0. 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}"
开发者_如何学JAVA IsReadOnly="True"/>
<DataGridCheckBoxColumn Header="Selected" Width="SizeToCells" MinWidth="100"
Binding="{Binding IsSelected}"
IsReadOnly="false"/>
</DataGrid.Columns>
</DataGrid>
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.
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
精彩评论