XAML 选择数据网格中的所有复选框

dgsult0t  于 2023-08-01  发布在  其他
关注(0)|答案(3)|浏览(91)

我试图选择所有的复选框在一个数据网格,但我没有得到任何结果使用此代码波纹管
这是我在单击主CheckBox时调用的函数

private void CheckUnCheckAll(object sender, RoutedEventArgs e)
{
    CheckBox chkSelectAll = ((CheckBox)sender);
    if (chkSelectAll.IsChecked == true)
    {
        dgUsers.Items.OfType<CheckBox>().ToList().ForEach(x => x.IsChecked = true);
    }
    else
    {
        dgUsers.Items.OfType<CheckBox>().ToList().ForEach(x => x.IsChecked = false);
    }
}

字符串
dgUsers是DataGrid,但我意识到可以找到任何复选框。
这是我用来在数据网格中创建CheckBox的XAML

<DataGrid.Columns>
    <DataGridCheckBoxColumn x:Name="col0" HeaderStyle="{StaticResource ColumnHeaderGripperStyle}">
         <DataGridCheckBoxColumn.HeaderTemplate>
              <DataTemplate>
                   <CheckBox Click="CheckUnCheckAll" >
                   </CheckBox>
              </DataTemplate>
         </DataGridCheckBoxColumn.HeaderTemplate>
    </DataGridCheckBoxColumn>
<DataGrid.Columns>


这是我的数据网格的图片


的数据
是否有一些方法来选择所有的复选框编程?

编辑我已经尝试关注this steps

你可以看到我的代码是一样的,但是对我不起作用

lmvvr0a8

lmvvr0a81#

**TLDR;**这就是你想要的,代码如下:

x1c 0d1x的数据
执行此操作的适当位置是ViewModel。您的CheckBox可以有三种状态,您希望使用所有这些状态:
1.选中-选中每个项目
1.未选中-未选中任何项目
1.不确定-某些项目已选中,某些项目未选中
您将希望在选中/取消选中某个项目时更新CheckBox,并在CheckBox发生更改时更新所有项目-仅以一种方式实现此操作将使CheckBox处于无效状态,这可能会对用户体验产生负面影响。我的建议是:一路走好,落实到位。要做到这一点,您需要知道是哪一个导致了更改-条目的CheckBox还是标题中的CheckBox。
我会这样做:
首先,你需要一个ViewModel用于你的项目,我在这里使用了一个非常简化的模型,它只包含IsChecked属性。

public class Entry : INotifyPropertyChanged
{
    private bool _isChecked;

    public bool IsChecked
    {
        get => _isChecked;
        set
        {
            if (value == _isChecked) return;
            _isChecked = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

字符串
您的主ViewModel将包含所有项的集合。每当一个项目的IsChecked属性发生变化时,您必须检查所有项目是否被选中/未选中,并更新头部中的CheckBox(或者更确切地说是其数据源的值)。

public class ViewModel : INotifyPropertyChanged
{
    public List<Entry> Entries
    {
        get => _entries;
        set
        {
            if (Equals(value, _entries)) return;
            _entries = value;
            OnPropertyChanged();
        }
    }

    public ViewModel()
    {
        // Just some demo data
        Entries = new List<Entry>
        {
            new Entry(),
            new Entry(),
            new Entry(),
            new Entry()
        };

        // Make sure to listen to changes. 
        // If you add/remove items, don't forgat to add/remove the event handlers too
        foreach (Entry entry in Entries)
        {
            entry.PropertyChanged += EntryOnPropertyChanged;
        }
    }

    private void EntryOnPropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        // Only re-check if the IsChecked property changed
        if(args.PropertyName == nameof(Entry.IsChecked))
            RecheckAllSelected();
    }

    private void AllSelectedChanged()
    {
        // Has this change been caused by some other change?
        // return so we don't mess things up
        if (_allSelectedChanging) return;

        try
        {
            _allSelectedChanging = true;

            // this can of course be simplified
            if (AllSelected == true)
            {
                foreach (Entry kommune in Entries)
                    kommune.IsChecked = true;
            }
            else if (AllSelected == false)
            {
                foreach (Entry kommune in Entries)
                    kommune.IsChecked = false;
            }
        }
        finally
        {
            _allSelectedChanging = false;
        }
    }

    private void RecheckAllSelected()
    {
        // Has this change been caused by some other change?
        // return so we don't mess things up
        if (_allSelectedChanging) return;

        try
        {
            _allSelectedChanging = true;

            if (Entries.All(e => e.IsChecked))
                AllSelected = true;
            else if (Entries.All(e => !e.IsChecked))
                AllSelected = false;
            else
                AllSelected = null;
        }
        finally
        {
            _allSelectedChanging = false;
        }
    }

    public bool? AllSelected
    {
        get => _allSelected;
        set
        {
            if (value == _allSelected) return;
            _allSelected = value;

            // Set all other CheckBoxes
            AllSelectedChanged();
            OnPropertyChanged();
        }
    }

    private bool _allSelectedChanging;
    private List<Entry> _entries;
    private bool? _allSelected;
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}


演示XAML:

<DataGrid ItemsSource="{Binding Entries}" AutoGenerateColumns="False" IsReadOnly="False" CanUserAddRows="False">
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Binding="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}">
            <DataGridCheckBoxColumn.HeaderTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:MainWindow}, Path=ViewModel.AllSelected}">Select All</CheckBox>
                </DataTemplate>
            </DataGridCheckBoxColumn.HeaderTemplate>
        </DataGridCheckBoxColumn>
    </DataGrid.Columns>
</DataGrid>

72qzrwbm

72qzrwbm2#

这是基于@Manfred的solution的修改。我使用Command而不是event
XAML:

<DataGrid ItemsSource="{Binding Students}" AutoGenerateColumns="True" CanUserAddRows="False">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.HeaderTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding DataContext.IsAllSelected, RelativeSource={RelativeSource AncestorType=DataGrid}}" Command="{Binding DataContext.CheckAllStudentsCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
                </DataTemplate>
            </DataGridTemplateColumn.HeaderTemplate>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" Command="{Binding DataContext.CheckStudentCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

字符串
视图模型:

public class MainWindowViewModel : INotifyPropertyChanged
{
    private List<Student> students;

    public List<Student> Students
    {
        get { return students; }
        set { students = value; OnPropertyChanged(); }
    }

    private bool? isAllSelected;

    public bool? IsAllSelected
    {
        get { return isAllSelected; }
        set { isAllSelected = value; OnPropertyChanged(); }
    }

    public RelayCommand CheckStudentCommand { get; private set; }
    public RelayCommand CheckAllStudentsCommand { get; private set; }

    public MainWindowViewModel()
    {
        Students = new List<Student>() { new Student { Name = "Walter" }, new Student { Name = "Jenny" }, new Student { Name = "Joe" } };
        CheckStudentCommand = new RelayCommand(OnCheckStudent);
        CheckAllStudentsCommand = new RelayCommand(OnCheckAllStudents);
        IsAllSelected = false;
    }

    private void OnCheckAllStudents()
    {
        if (IsAllSelected == true)
            Students.ForEach(x => x.IsChecked = true);
        else
            Students.ForEach(x => x.IsChecked = false);
    }

    private void OnCheckStudent()
    {
        if (Students.All(x => x.IsChecked))
            IsAllSelected = true;
        else if (Students.All(x => !x.IsChecked))
            IsAllSelected = false;
        else
            IsAllSelected = null;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}


源代码可用here

332nm8kg

332nm8kg3#

您在示例中所做的是遍历数据项,而不是遍历控件(我假设您没有ItemsSource控件)。
在您发布的链接中,YourClass是ViewModel的类,网格行的数据对象。
这一个应该在你这边用最少的代码更改就可以工作(但我更喜欢在ViewModel中使用类似CheckUncheckCommand +将IsChecked绑定到CommandParameter**的东西来处理它):

<DataGridCheckBoxColumn x:Name="col0" HeaderStyle="{StaticResource ColumnHeaderGripperStyle}" DisplayIndex="0">

private void CheckUnCheckAll(object sender, RoutedEventArgs e)
{
    var chkSelectAll = sender as CheckBox;
    var firstCol = dgUsers.Columns.OfType<DataGridCheckBoxColumn>().FirstOrDefault(c => c.DisplayIndex == 0);
    if (chkSelectAll == null || firstCol == null || dgUsers?.Items == null)
    {
        return;
    }
    foreach (var item in dgUsers.Items)
    {
        var chBx = firstCol.GetCellContent(item) as CheckBox;
        if (chBx == null)
        {
            continue;
        }
        chBx.IsChecked = chkSelectAll.IsChecked;
    }
}

字符串

相关问题