【问题标题】:How to perform Single click checkbox selection in WPF DataGrid with IEditableObject object如何使用 IEditableObject 对象在 WPF DataGrid 中执行单击复选框选择
【发布时间】:2017-08-10 21:39:54
【问题描述】:

DataGridCheckBoxColumn 的默认行为是用户必须单击两次才能更改复选框值。在How to perform Single click checkbox selection in WPF DataGrid 主题中,有几个可行的解决方案,但有一个问题 - 你在代码后面有一个视图模型对象,它实现了IEditableObject 接口,然后EndEdit 方法不执行。

知道如何使单击工作并保留IEditableObject 功能吗?

【问题讨论】:

    标签: c# wpf mvvm datagrid viewmodel


    【解决方案1】:

    您可以为DataGrid 处理GotFocus 事件并显式进入编辑模式并选中/取消选中CheckBox

    private void dg_GotFocus(object sender, RoutedEventArgs e)
    {
        DataGridCell cell = e.OriginalSource as DataGridCell;
        if (cell != null && cell.Column is DataGridCheckBoxColumn)
        {
            dg.BeginEdit();
            CheckBox chkBox = cell.Content as CheckBox;
            if (chkBox != null)
            {
                chkBox.IsChecked = !chkBox.IsChecked;
            }
        }
    }
    

    <DataGrid x:Name="dg" AutoGenerateColumns="False" GotFocus="dg_GotFocus">
        <DataGrid.Columns>
            <DataGridCheckBoxColumn Binding="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" />
            ...
    

    【讨论】:

      【解决方案2】:

      对所有复选框使用相同的方法

      private void GotFocus(object sender, RoutedEventArgs e)
              {
                  var sen = sender as DataGrid;
                  DataGridCell cell = e.OriginalSource as DataGridCell;
                  if (cell != null && cell.Column is DataGridCheckBoxColumn)
                  {
                      sen.BeginEdit();
                      CheckBox chkBox = cell.Content as CheckBox;
                      if (chkBox != null)
                      {
                          chkBox.IsChecked = !chkBox.IsChecked;
                      }
                  }
              }
      

      【讨论】:

        猜你喜欢
        • 2011-04-19
        • 2011-11-21
        • 2019-12-06
        • 1970-01-01
        • 1970-01-01
        • 2018-08-03
        • 1970-01-01
        • 2013-11-01
        相关资源
        最近更新 更多