2

我在 c# 4.0 中使用 aDataGrid和 a 。CheckBoxColumn现在,CheckBox如果启用行选择,我需要单击 2 次来更改 a 的状态。

一键选择行,二键更改状态CheckBox。如何启用行选择,但保持 1 单击以更改状态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>
4

2 回答 2

2

看看这个问题的公认答案 - 它使用带有标准 CheckBox 的 DataTemplateColumn 而不是 CheckBoxColumn。这使您可以单击编辑,并且如果您启用了行选择,它也可以工作。HTH。

于 2010-07-09T20:56:54.503 回答
0

好的,因为没有人愿意为此提供一个好的答案:) 这是一个技巧\hack,它应该可以满足您的需要:

将 SelectedCellsChanged 事件处理程序添加到您的网格:

SelectedCellsChanged="gridPersons_SelectedCellsChanged"

下面是事件处理程序的代码,它将使选定的单元格进入编辑模式并模拟额外的鼠标单击它会切换复选框。

[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);
}

希望这会有所帮助,问候

于 2009-11-15T00:44:07.667 回答