在WPF DataGrid中如何通过DataGrid Header CheckBox选择一列的所有复选框

9

我有一个带有一个CheckBoxColumn的DataGrid。在该CheckBoxColumn的标题中,我添加了一个CheckBox来选择该Datagrid行的所有复选框。

我该如何实现这个功能?

我的WPF dataGrid的XAML代码:

    <DataGrid AutoGenerateColumns="False" CanUserAddRows="False"  Grid.RowSpan="2" Height="130" HorizontalAlignment="Left" IsReadOnly="False" Margin="189,340,0,0" Name="dgCandidate" TabIndex="7" VerticalAlignment="Top" Width="466" Grid.Row="1" >
        <DataGrid.Columns>
            <DataGridTextColumn x:Name="colCandidateID" Binding="{Binding CandidateID}" Header="SlNo" MinWidth="20" IsReadOnly="True" />
            <DataGridTextColumn x:Name="colRegistraion" Binding="{Binding RegisterNo}" Header="Reg. No." IsReadOnly="True"  />
            <DataGridTextColumn x:Name="colCandidate" Binding="{Binding CandidateName}" Header="Name" MinWidth="250" IsReadOnly="True"  />

            <DataGridTemplateColumn>
                <DataGridTemplateColumn.Header>
                    <CheckBox Name="chkSelectAll" Checked="chkSelectAll_Checked" Unchecked="chkSelectAll_Unchecked"></CheckBox>
                </DataGridTemplateColumn.Header>
                <DataGridTemplateColumn.CellTemplate >
                    <DataTemplate >
                        <CheckBox x:Name="colchkSelect1" Checked="colchkSelect1_Checked" Unchecked="colchkSelect1_Unchecked" ></CheckBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

        </DataGrid.Columns>

    </DataGrid>
4个回答

7
将您的Candidate类转换为以下形式:
public class Candidate : DependencyObject
{
    //CandidateID Dependency Property
    public int CandidateID
    {
        get { return (int)GetValue(CandidateIDProperty); }
        set { SetValue(CandidateIDProperty, value); }
    }
    public static readonly DependencyProperty CandidateIDProperty =
        DependencyProperty.Register("CandidateID", typeof(int), typeof(Candidate), new UIPropertyMetadata(0));
    //RegisterNo Dependency Property
    public int RegisterNo
    {
        get { return (int)GetValue(RegisterNoProperty); }
        set { SetValue(RegisterNoProperty, value); }
    }
    public static readonly DependencyProperty RegisterNoProperty =
        DependencyProperty.Register("RegisterNo", typeof(int), typeof(Candidate), new UIPropertyMetadata(0));
    //CandidateName Dependency Property
    public string CandidateName
    {
        get { return (string)GetValue(CandidateNameProperty); }
        set { SetValue(CandidateNameProperty, value); }
    }
    public static readonly DependencyProperty CandidateNameProperty =
        DependencyProperty.Register("CandidateName", typeof(string), typeof(Candidate), new UIPropertyMetadata(""));
    //BooleanFlag Dependency Property
    public bool BooleanFlag
    {
        get { return (bool)GetValue(BooleanFlagProperty); }
        set { SetValue(BooleanFlagProperty, value); }
    }
    public static readonly DependencyProperty BooleanFlagProperty =
        DependencyProperty.Register("BooleanFlag", typeof(bool), typeof(Candidate), new UIPropertyMetadata(false));
}

在 MainWindow.xaml 中:

<DataGrid ItemsSource="{Binding CandidateList}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Id" Binding="{Binding CandidateID}"/>
        <DataGridTextColumn Header="RegNr" Binding="{Binding RegisterNo}"/>
        <DataGridTextColumn Header="Name" Binding="{Binding CandidateName}"/>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.Header>
                <CheckBox Checked="CheckBox_Checked" Unchecked="CheckBox_Checked"></CheckBox>
            </DataGridTemplateColumn.Header>
            <DataGridTemplateColumn.CellTemplate >
                <DataTemplate>
                    <CheckBox IsChecked="{Binding BooleanFlag}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

在MainWindow.xaml.cs中:

    public MainWindow()
    {
        DataContext = this;
        CandidateList.Add(new Candidate()
        {
            CandidateID = 1,
            CandidateName = "Jack",
            RegisterNo = 123,
            BooleanFlag = true
        });
        CandidateList.Add(new Candidate()
        {
            CandidateID = 2,
            CandidateName = "Jim",
            RegisterNo = 234,
            BooleanFlag = false
        });
        InitializeComponent();
    }
    //List Observable Collection
    private ObservableCollection<Candidate> _candidateList = new ObservableCollection<Candidate>();
    public ObservableCollection<Candidate> CandidateList { get { return _candidateList; } }
    private void CheckBox_Checked(object sender, RoutedEventArgs e)
    {
        foreach (var item in CandidateList)
        {
            item.BooleanFlag = true;
        }
    }
    private void UnheckBox_Checked(object sender, RoutedEventArgs e)
    {
        foreach (var item in CandidateList)
        {
            item.BooleanFlag = false;
        }
    }

这应该是您DataGrid的源。(最好定义为ObservableCollection<MyItemType>) 另外,MyBooleanProperty应该是一个DependencyProperty,它在继承自DependencyObject的MyItemType中定义。如果太混乱了,请告诉我以便发布更详细的答案。 - Bizhan
谢谢。实际上,我对这个还不太熟悉,所以有些东西让我感到困惑,请再详细解释一下… - Avinash Singh
1
为了使绑定工作,您需要将数据类型定义为DependecyObjects,将属性定义为DependencyProperty。尽可能避免使用x:Name,而是使用Binding。如果必须为xaml元素提供列表,请不要通过编写循环来填充元素的“Items”,而是使用ItemsSource =“{Binding someList}”。someList应该是一个ObservableCollection<someType>。someType应该继承自DependencyObject。最后,您需要为xaml设置DataContext,我更喜欢在*.xaml.cs文件中进行设置,就像我在构造函数中所做的那样。 - Bizhan
注意:要定义一个依赖属性,请使用propdp代码片段。(输入propdp,按两次Tab键,然后填写高亮部分。) - Bizhan
非常感谢,它正在运行中,我将在我的项目中与 SQL 表一起实现。 - Avinash Singh

3

严格来说,模型不应知道视图,因此blindmeis提出的解决方案,在数据网格中更新每一行的模型更改,破坏了MVVM / Presentation设计模式。请记住,在MVVM中,依赖关系流是View -> ViewModel -> Model,因此,如果您在视图模型(或控件代码后台)中引用控件,则实际上已经破坏了模式,并且在后面可能会遇到问题。


2
我已经在Datagrid行中添加了CheckBox以选择所有的CheckBox。
如果你的意思是选择Datagrid列中的所有复选框,那么我会建议:只需更新你的itemssource集合为选中/取消选中即可。
public bool SelectAll
{
  get{return this._selectAll;}
  set
  {
     this._selectAll = value;
     this.MyItemsSourceCollection.ForEach(x=>x.MyRowCheckProperty=value);
     this.OnPropertyChanged("SelectAll");
  }
}

XAML

        <DataGridTemplateColumn>
            <DataGridTemplateColumn.Header>
                <CheckBox isChecked="{Binding SelectAll}"></CheckBox>
            </DataGridTemplateColumn.Header>
            <DataGridTemplateColumn.CellTemplate >
                <DataTemplate >
                    <CheckBox IsChecked="{Binding MyRowCheckProperty}"></CheckBox>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

我不确定XAML绑定是否正确,但我希望您能理解我的意图。


它显示错误,不包含MyItemsSourceCollection的定义。 - Avinash Singh
这是一个示例,您需要使用自己的属性名称。 - blindmeis
DataGridTemplateColumn绑定到该项,所以除非你的项上有SelectAll,否则isChecked="{Binding SelectAll}"是行不通的。你必须通过引用VM,比如通过x:Name属性<DataGrid x:Name="mydg" .... > ... isChecked="{Binding ElementName=mydg, Path=DataContext.SelectAll} - undefined

1
这个问题比人们想象的要困难得多。首先,您不能仅将视图模型绑定到列标题,因为它没有视图模型作为其数据上下文,所以您需要一个绑定代理来正确地将绑定路由到视图模型。
public class BindingProxy : Freezable
{
    public static readonly DependencyProperty DataProperty = DependencyProperty.Register(
        "Data", 
        typeof(object), 
        typeof(BindingProxy),
        new UIPropertyMetadata(null));

    public object Data
    {
        get { return this.GetValue(DataProperty); }
        set { this.SetValue(DataProperty, value); }
    }

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }
}

现在在您的数据网格资源中创建一个绑定代理:
<DataGrid.Resources>
    <aon:BindingProxy
        x:Key="DataContextProxy"
        Data="{Binding}" />
</DataGrid.Resources>

然后需要将该列定义为:
<DataGridTemplateColumn>
    <DataGridTemplateColumn.HeaderTemplate>
        <DataTemplate>
            <CheckBox
                Command="{Binding
                    Data.SelectAllCommand,
                    Source={StaticResource DataContextProxy}}"
                IsChecked="{Binding
                    Data.AreAllSelected,
                    Mode=OneWay,
                    Source={StaticResource DataContextProxy},
                    UpdateSourceTrigger=PropertyChanged}"
                IsThreeState="True" />
        </DataTemplate>
    </DataGridTemplateColumn.HeaderTemplate>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox
                IsChecked="{Binding
                    Path=IsSelected,
                    UpdateSourceTrigger=PropertyChanged}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

注意需要同时绑定复选框的IsChecked依赖属性和Command属性,并且IsChecked绑定为单向绑定。IsChecked绑定使复选框显示当前项的状态,而Command绑定执行批量选择。两者都是必需的。
现在,在视图模型中:
public bool? AreAllSelected
{
    get
    {
        return this.Items.All(candidate => candidate.IsSelected)
        ? true
        : this.Items.All(candidate => !candidate.IsSelected)
            ? (bool?)false
            : null;
    }

    set
    {
        if (value != null)
        {
            foreach (var item in this.Items)
            {
                item.IsSelected = value.Value;
            }
        }

        this.RaisePropertyChanged();
    }
}

SelectAllCommand 属性是 ICommand 的实现,其中 Execute 方法为:

public void Execute(object parameter)
{
    var allSelected = this.AreAllSelected;

    switch (allSelected)
    {
        case true:
            this.AreAllSelected = false;
            break;
        case false:
        case null:
            this.AreAllSelected = true;
            break;
    }
}

最后,你的行项视图模型(即Items中的内容)需要在每次IsSelected的值更改时向主视图模型引发PropertyChanged。如何实现这一点基本上取决于你自己。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接