如何在一次单击中禁用行选择并启用复选框?

时间:2013-06-05 10:36:10

标签: c# wpf mvvm datagrid

我正在尝试在WPF MVVM中创建一个包含信息行的数据网格,而Columns是一个代表DataGridCheckBoxColumn属性的Boolean

我希望能够点击一个复选框,并在一次点击中将其更改为“已选中”。 我还想禁用选择行的选项,也禁用在其他列中更改其他内容的选项。

请建议。

2 个答案:

答案 0 :(得分:0)

以此答案为出发点:How to perform Single click checkbox selection in WPF DataGrid?

我做了一些修改并结束了这个:

WPF:

<DataGrid.Resources>
  <Style TargetType="{x:Type DataGridRow}">
    <EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridRow_PreviewMouseLeftButtonDown"/>
  </Style>
  <Style TargetType="{x:Type DataGridCell}">
    <EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown"/>
  </Style>
</DataGrid.Resources>

代码背后:

    private void DataGridRow_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        DataGridRow row = sender as DataGridRow;
        if (row == null) return;
        if (row.IsEditing) return;
        if (!row.IsSelected) row.IsSelected = true; // you can't select a single cell in full row select mode, so instead we have to select the whole row
    }

    private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        DataGridCell cell = sender as DataGridCell;
        if (cell == null) return;
        if (cell.IsEditing) return;
        if (!cell.IsFocused) cell.Focus(); // you CAN focus on a single cell in full row select mode, and in fact you HAVE to if you want single click editing.
        //if (!cell.IsSelected) cell.IsSelected = true; --> can't do this with full row select.  You HAVE to do this for single cell selection mode.
    }

尝试一下,看看它是否符合您的要求。

答案 1 :(得分:0)

DataGridCheckBoxColumn默认情况下以这种方式工作。第一次单击选择行或单元格,第二次单击更改复选框状态。有时是需要的:例如,当您需要在使用复选框之前调用选择更改的事件时。 为了创建一个复选框列,该复选框在第一次单击时会发生更改,最好将DataGridTemplateColumn与CheckBox用作单元格模板:

n=10