You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UWP/WinUI DataGrid如何实现全选?类似WPF的dataGrid.SelectAll()

在UWP/WinUI DataGrid中实现全选所有行的方法

UWP和WinUI的DataGrid控件确实没有内置类似WPF的SelectAll()方法,你可以通过以下两种常见方式实现全选逻辑:

1. MVVM模式下(绑定IsSelected属性)

如果你的数据模型实现了INotifyPropertyChanged,并通过DataGridRow.IsSelected绑定到模型的属性,直接遍历数据源修改选中状态即可:

步骤1:定义带IsSelected属性的数据模型

public class YourDataModel : INotifyPropertyChanged
{
    private bool _isSelected;
    public bool IsSelected
    {
        get => _isSelected;
        set
        {
            if (_isSelected != value)
            {
                _isSelected = value;
                OnPropertyChanged(nameof(IsSelected));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    // 其他业务属性
}

步骤2:XAML中绑定行的IsSelected属性

<controls:DataGrid 
    ItemsSource="{Binding YourItemCollection}"
    SelectionMode="Extended"> <!-- 确保选择模式不是Single -->
    <controls:DataGrid.RowStyle>
        <Style TargetType="controls:DataGridRow">
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
        </Style>
    </controls:DataGrid.RowStyle>
    <!-- 列定义 -->
</controls:DataGrid>

步骤3:实现全选逻辑

// 遍历数据源,设置所有项的IsSelected为true
foreach (var item in YourItemCollection)
{
    item.IsSelected = true;
}

2. 直接操作DataGrid控件(代码后台)

如果没有使用MVVM绑定,可直接操作SelectedItems集合来实现全选,这种方式不受UI虚拟化影响,更可靠:

// 确保DataGrid的选择模式为Extended或Multiple
dataGrid.SelectionMode = DataGridSelectionMode.Extended;

// 清空现有选中项,再添加所有数据源项
dataGrid.SelectedItems.Clear();
foreach (var item in dataGrid.Items)
{
    dataGrid.SelectedItems.Add(item);
}

注意事项

  • 必须确保DataGrid.SelectionMode设置为Extended或Multiple,Single模式下无法多选。
  • 处理大数据量时,建议在UI线程执行(因为涉及控件属性修改),若数据量极大可考虑分批处理避免UI卡顿。

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 21:05:37