【问题标题】:How to disable row selection and enable checkbox in one click?如何一键禁用行选择并启用复选框?
【发布时间】:2013-06-05 10:36:09
【问题描述】:

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

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

请指教。

【问题讨论】:

    标签: c# wpf mvvm datagrid


    【解决方案1】:

    以此答案为起点: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.
        }
    

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

    【讨论】:

      【解决方案2】:

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

                                  <DataGridTemplateColumn Header="ChBoxColumn">
                                      <DataGridTemplateColumn.CellTemplate>
                                          <DataTemplate>
                                              <CheckBox Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" HorizontalAlignment="Center" VerticalAlignment="Center"></CheckBox>
                                          </DataTemplate>
                                      </DataGridTemplateColumn.CellTemplate>
                                  </DataGridTemplateColumn>
      

      【讨论】:

        猜你喜欢
        • 2013-11-17
        • 1970-01-01
        • 2011-08-28
        • 1970-01-01
        • 2015-02-03
        • 2014-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多