【问题标题】:WPF checkbox all not not updating on one checkbox row is unchecked未选中所有未在一个复选框行上更新的 WPF 复选框
【发布时间】:2015-08-10 07:48:32
【问题描述】:

我在 WPF C# 的数据网格内有一个复选框。

                     <DataGridCheckBoxColumn Binding="{Binding IsSelected,UpdateSourceTrigger=PropertyChanged}" CanUserSort="False">
                    <DataGridCheckBoxColumn.ElementStyle>
                        <Style TargetType="CheckBox" BasedOn="{StaticResource {x:Type CheckBox}}">
                            <Setter Property="VerticalAlignment" Value="Center"/>
                            <Setter Property="HorizontalAlignment" Value="Center"/>
                        </Style>
                    </DataGridCheckBoxColumn.ElementStyle>
                    <DataGridCheckBoxColumn.HeaderTemplate>
                        <DataTemplate x:Name="dtAllChkBx">
                            <CheckBox Name="cbxAll" HorizontalAlignment="Center" Margin="0,0,5,0" IsEnabled="{Binding Path=DataContext.IsCbxAllEnabled,RelativeSource={RelativeSource AncestorType=DataGrid}}"
                                      IsChecked="{Binding Path=DataContext.AllSelected,RelativeSource={RelativeSource AncestorType=DataGrid},UpdateSourceTrigger=PropertyChanged}"/>
                        </DataTemplate>
                    </DataGridCheckBoxColumn.HeaderTemplate>
                </DataGridCheckBoxColumn>

当我选中 All 复选框时,它当然会标记所有复选框,但是一旦我取消选中一个复选框,All 复选框仍然处于选中状态。这应该是未选中的。我应该如何使用 WPF C# 来做到这一点。

【问题讨论】:

  • 我们能看到 AllSelected 属性的代码吗?
  • @GlenThomas private bool _AllSelected; public bool AllSelected { get { return _AllSelected; } 设置 { _AllSelected = 值; TaskList.ToList().ForEach(x => x.IsSelected = value); NotifyOfPropertyChange(() => AllSelected); } }
  • AllSelected 属性用于全选和取消全选。
  • TaskList项的IsSelected值是否有NotifyOfPropertyChange?
  • 编写复选框逻辑的完整代码。不知道我在哪里做错了

标签: c# wpf checked


【解决方案1】:

如果我理解正确 - 在集合项内的 IsSelected 属性发生任何更改后,您应该更新 AllSelected 值。

因此,您需要在所有项目(事件或操作或您想要的任何机制)中进行一些回调,并更改 AllSelectedget 逻辑

这是项目 IsSelected 属性和构造函数的一些草稿:

public bool IsSelected {
    get { return isSelected; }
    set {
        isSelected = value;
        OnPropertyChanged();
        if (globalUpdate != null) globalUpdate();
    }
}

public ItemClass(Action globalUpdate, ...your parameters) {
    this.globalUpdate = globalUpdate;
    ...do smth with your parameters
}

使用示例:

new ItemClass(() => OnPropertyChanged("AllSelected"))

当然不要忘记 AllSelected getter

public bool AllSelected {
        get { return YourGridItemsCollection.All(item => item.IsSelected); }

现在,当您手动检查所有项目时,AllSelected 将被自动选中,并且在您取消选中任何项目时取消选中。

【讨论】:

  • 那你的问题是什么?
  • 问题是当我选中 AllSelected 复选框时,该列中的所有复选框都被选中,但是如果我取消选中该列中任何行的任何复选框,AllSelected 复选框不会被取消选中
  • 所提供的解决方案正是为此。您应该将行内的更改通知 AllSelected 复选框并稍微修改其 getter。请仔细阅读我的回答。
猜你喜欢
  • 2015-08-25
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
  • 2012-05-12
  • 2020-01-05
  • 2019-02-02
相关资源
最近更新 更多