在 WPF 数据网格标题中添加一个复选框,并使用它来选择/取消选择 DataGridCheckBoxColumn 中的所有复选框

发布于 2024-12-17 08:48:22 字数 855 浏览 1 评论 0原文

我是 WPF 新手,希望能帮助解决以下问题。

在我的 wpf datagrid 中,我将 DataGridCheckBoxColumn 作为第一列,并且我已将此列绑定到 ViewModel 中的 IsSelected 属性。

<toolkit:DataGridCheckBoxColumn Header="Title" Binding="{Binding isSelected}"/>

我还想在标题行中有一个复选框,我打算用它来选择/取消选择此列中的所有复选框。

到目前为止,我已经设法通过应用标题样式在标题中获得一个复选框,如下面的代码片段所示,但我无法切换列中所有复选框的选择

<Style x:Key="CheckBoxHeaderStyle" TargetType="{x:Type toolkit:DataGridColumnHeader}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type toolkit:DataGridColumnHeader}">
                <CheckBox x:Name="chkToggleSelection"   VerticalAlignment="Center">
                </CheckBox>
            </ControlTemplate>
        </Setter.Value>
     </Setter>
 </Style>

I am new to WPF and would appreciate help on following problem.

In my wpf datagrid I have DataGridCheckBoxColumn as first column and I have bind this column to IsSelected property in ViewModel.

<toolkit:DataGridCheckBoxColumn Header="Title" Binding="{Binding isSelected}"/>

I also want to have a checkbox in header row and which I intend to use to select/unselect all the checkboxes in this column.

Till now I have managed to get a checkbox in header by applying a headerstyle as shown in below code snip but I am not able to toggle selection for all the checkboxes in column

<Style x:Key="CheckBoxHeaderStyle" TargetType="{x:Type toolkit:DataGridColumnHeader}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type toolkit:DataGridColumnHeader}">
                <CheckBox x:Name="chkToggleSelection"   VerticalAlignment="Center">
                </CheckBox>
            </ControlTemplate>
        </Setter.Value>
     </Setter>
 </Style>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花辞树 2024-12-24 08:48:22

您必须处理 Checkbox.Click 事件(如果您使用 MVVM,则设置 CheckBox.Command 或使用附加行为来处理该事件),然后设置布尔值绑定到数据网格的所有项目的属性相应地为 true \ false。

可悲的是,据我所知,没有其他选择!

You will have to handle the Checkbox.Click event (if you are using MVVM then set the CheckBox.Command or use attached behavior to handle the event) and then set the boolean property of all items bound to the datagrid as true \ false accordingly.

Sadly there is no other alternative that I am aware of!

千柳 2024-12-24 08:48:22
<DataGrid x:Name="DgLines" ItemsSource="{Binding OpcUaEndpoints}" AutoGenerateColumns="False"
                     SelectionMode="Extended"  IsReadOnly="True" Grid.ColumnSpan="5">
                        <DataGrid.Columns>
                            <DataGridTemplateColumn>
                                <DataGridTemplateColumn.HeaderTemplate>
                                <DataTemplate>
                                    <CheckBox Name="ckbSelectedAll" 
                                          IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}">
                                            <i:Interaction.Triggers>
                                                <i:EventTrigger EventName="Checked" >
                                                    <i:InvokeCommandAction Command="{Binding DataContext.CheckedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" />
                                                </i:EventTrigger>
                                                <i:EventTrigger EventName="Unchecked" >
                                                    <i:InvokeCommandAction Command="{Binding DataContext.UncheckedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" />
                                                </i:EventTrigger>
                                            </i:Interaction.Triggers>
                                        </CheckBox>
                                </DataTemplate>
                                </DataGridTemplateColumn.HeaderTemplate>
                                <DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                        <CheckBox Name="cbkSelect" 
                                          IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}"/>
                                    </DataTemplate>
                                </DataGridTemplateColumn.CellTemplate>
                            </DataGridTemplateColumn>

                            <!--<DataGridTextColumn Width="200" Header="Id" Binding="{Binding Id }" />-->

                            <DataGridTextColumn Width="200" Header="Name" Binding="{Binding Name}"/>
                            <DataGridTextColumn Width="500" Header="Description" Binding="{Binding Description}"/>
                            <DataGridTextColumn Width="500" Header="Lines" Binding="{Binding Endpoint}"/>
                        </DataGrid.Columns>
                    </DataGrid>


        public class OpcUaEndpointsListViewModel : INotifyPropertyChanged
            {
                private static OpcUaEndpointsListViewModel _instance;
                private static readonly object Padlock = new object();
                private ICommand _addCommand;
                //private ICommand _uncheckCommand;
                private ICommand _searchcommand;
                private ICommand _checkedCommand { get; set; }
                private ICommand _unCheckedCommand { get; set; }

                private ObservableCollection<AddOpcUaEndpointsViewModel> _endpoint;
                public string _charNameFromTB;

                public event PropertyChangedEventHandler PropertyChanged;

                public OpcUaEndpointsListViewModel()
                {
                    BindDataGrid();
                }

                public static OpcUaEndpointsListViewModel Instance
                {
                    get
                    {
                        lock (Padlock)
                        {
                            return _instance ?? (_instance = new OpcUaEndpointsListViewModel());
                        }
                    }
                }

                /// <summary>
                ///     //OPC UA Endpoint List
                /// </summary>
                public ObservableCollection<AddOpcUaEndpointsViewModel> OpcUaEndpoints
                {
                    get { return _endpoint; }
                    set
                    {
                        if (OpcUaEndpoints == value)
                        {
                            _endpoint = value;
                            OnPropertyChanged("OpcUaEndpoints");
                        }
                    }
                }

                public string CharNameFromTB
                {
                    get { return _charNameFromTB; }
                    set
                    {
                        _charNameFromTB = value;
                        OnPropertyChanged("CharNameFromTB");
                    }
                }

                public ICommand AddCommand
                {
                    get { return _addCommand ?? (_addCommand = new WpfApplication1.RelayCommand<object>(p => ExecuteAddCommand())); }
                }

                public ICommand SearchCommand
                {
                    get { return _searchcommand ?? (_searchcommand = new RelayCommand<object>(p => ExecuteSearchCommand())); }
                }


                public ICommand CheckedCommand
                {
                    get { return _checkedCommand ?? (_checkedCommand = new WpfApplication1.RelayCommand<object>(p => ExecuteCheckedCommand())); }
                }
                public ICommand UncheckedCommand
                {
                    get { return _unCheckedCommand ?? (_unCheckedCommand = new WpfApplication1.RelayCommand<object>(p => ExecuteUnCheckedCommand())); }
                }


                private void ExecuteSearchCommand()
                {
                    ///BindDataGridsearch();
                }

                private void ExecuteCheckedCommand()
                {
                    foreach (var item in _endpoint)
                    {
                        item.IsSelected = true;
                    }
                }

                private void ExecuteUnCheckedCommand()
                {
                    foreach (var item in _endpoint)
                    {
                        item.IsSelected = false;
                    }
                }

                private void ExecuteAddCommand()
                {
                    ///BindDataGridsearch();
                }

                private void BindDataGrid()
                {
                    _endpoint = new ObservableCollection<AddOpcUaEndpointsViewModel>();
                    _endpoint.Add(new AddOpcUaEndpointsViewModel { Name = "A", Description = "A", Endpoint = 1 });
                    _endpoint.Add(new AddOpcUaEndpointsViewModel { Name = "B", Description = "B", Endpoint = 2 });
                    _endpoint.Add(new AddOpcUaEndpointsViewModel { Name = "C", Description = "C", Endpoint = 3 });
                    _endpoint.Add(new AddOpcUaEndpointsViewModel { Name = "D", Description = "D", Endpoint = 4 });
                    _endpoint.Add(new AddOpcUaEndpointsViewModel { Name = "E", Description = "E", Endpoint = 5 });
                }

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

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

        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; OnPropertyChanged("Name"); }
        }

        private string _description;

        public string Description
        {
            get { return _description; }
            set { _description = value; OnPropertyChanged("Description"); }
        }

        private int _endPoint;

        public int Endpoint
        {
            get { return _endPoint; }
            set { _endPoint = value; OnPropertyChanged("Endpoint"); }
        }

        private bool _isSelected;

        public bool IsSelected
        {
            get { return _isSelected; }
            set { _isSelected = value; OnPropertyChanged("IsSelected"); }
        }
    }
<DataGrid x:Name="DgLines" ItemsSource="{Binding OpcUaEndpoints}" AutoGenerateColumns="False"
                     SelectionMode="Extended"  IsReadOnly="True" Grid.ColumnSpan="5">
                        <DataGrid.Columns>
                            <DataGridTemplateColumn>
                                <DataGridTemplateColumn.HeaderTemplate>
                                <DataTemplate>
                                    <CheckBox Name="ckbSelectedAll" 
                                          IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}">
                                            <i:Interaction.Triggers>
                                                <i:EventTrigger EventName="Checked" >
                                                    <i:InvokeCommandAction Command="{Binding DataContext.CheckedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" />
                                                </i:EventTrigger>
                                                <i:EventTrigger EventName="Unchecked" >
                                                    <i:InvokeCommandAction Command="{Binding DataContext.UncheckedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" />
                                                </i:EventTrigger>
                                            </i:Interaction.Triggers>
                                        </CheckBox>
                                </DataTemplate>
                                </DataGridTemplateColumn.HeaderTemplate>
                                <DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                        <CheckBox Name="cbkSelect" 
                                          IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}"/>
                                    </DataTemplate>
                                </DataGridTemplateColumn.CellTemplate>
                            </DataGridTemplateColumn>

                            <!--<DataGridTextColumn Width="200" Header="Id" Binding="{Binding Id }" />-->

                            <DataGridTextColumn Width="200" Header="Name" Binding="{Binding Name}"/>
                            <DataGridTextColumn Width="500" Header="Description" Binding="{Binding Description}"/>
                            <DataGridTextColumn Width="500" Header="Lines" Binding="{Binding Endpoint}"/>
                        </DataGrid.Columns>
                    </DataGrid>


        public class OpcUaEndpointsListViewModel : INotifyPropertyChanged
            {
                private static OpcUaEndpointsListViewModel _instance;
                private static readonly object Padlock = new object();
                private ICommand _addCommand;
                //private ICommand _uncheckCommand;
                private ICommand _searchcommand;
                private ICommand _checkedCommand { get; set; }
                private ICommand _unCheckedCommand { get; set; }

                private ObservableCollection<AddOpcUaEndpointsViewModel> _endpoint;
                public string _charNameFromTB;

                public event PropertyChangedEventHandler PropertyChanged;

                public OpcUaEndpointsListViewModel()
                {
                    BindDataGrid();
                }

                public static OpcUaEndpointsListViewModel Instance
                {
                    get
                    {
                        lock (Padlock)
                        {
                            return _instance ?? (_instance = new OpcUaEndpointsListViewModel());
                        }
                    }
                }

                /// <summary>
                ///     //OPC UA Endpoint List
                /// </summary>
                public ObservableCollection<AddOpcUaEndpointsViewModel> OpcUaEndpoints
                {
                    get { return _endpoint; }
                    set
                    {
                        if (OpcUaEndpoints == value)
                        {
                            _endpoint = value;
                            OnPropertyChanged("OpcUaEndpoints");
                        }
                    }
                }

                public string CharNameFromTB
                {
                    get { return _charNameFromTB; }
                    set
                    {
                        _charNameFromTB = value;
                        OnPropertyChanged("CharNameFromTB");
                    }
                }

                public ICommand AddCommand
                {
                    get { return _addCommand ?? (_addCommand = new WpfApplication1.RelayCommand<object>(p => ExecuteAddCommand())); }
                }

                public ICommand SearchCommand
                {
                    get { return _searchcommand ?? (_searchcommand = new RelayCommand<object>(p => ExecuteSearchCommand())); }
                }


                public ICommand CheckedCommand
                {
                    get { return _checkedCommand ?? (_checkedCommand = new WpfApplication1.RelayCommand<object>(p => ExecuteCheckedCommand())); }
                }
                public ICommand UncheckedCommand
                {
                    get { return _unCheckedCommand ?? (_unCheckedCommand = new WpfApplication1.RelayCommand<object>(p => ExecuteUnCheckedCommand())); }
                }


                private void ExecuteSearchCommand()
                {
                    ///BindDataGridsearch();
                }

                private void ExecuteCheckedCommand()
                {
                    foreach (var item in _endpoint)
                    {
                        item.IsSelected = true;
                    }
                }

                private void ExecuteUnCheckedCommand()
                {
                    foreach (var item in _endpoint)
                    {
                        item.IsSelected = false;
                    }
                }

                private void ExecuteAddCommand()
                {
                    ///BindDataGridsearch();
                }

                private void BindDataGrid()
                {
                    _endpoint = new ObservableCollection<AddOpcUaEndpointsViewModel>();
                    _endpoint.Add(new AddOpcUaEndpointsViewModel { Name = "A", Description = "A", Endpoint = 1 });
                    _endpoint.Add(new AddOpcUaEndpointsViewModel { Name = "B", Description = "B", Endpoint = 2 });
                    _endpoint.Add(new AddOpcUaEndpointsViewModel { Name = "C", Description = "C", Endpoint = 3 });
                    _endpoint.Add(new AddOpcUaEndpointsViewModel { Name = "D", Description = "D", Endpoint = 4 });
                    _endpoint.Add(new AddOpcUaEndpointsViewModel { Name = "E", Description = "E", Endpoint = 5 });
                }

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

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

        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; OnPropertyChanged("Name"); }
        }

        private string _description;

        public string Description
        {
            get { return _description; }
            set { _description = value; OnPropertyChanged("Description"); }
        }

        private int _endPoint;

        public int Endpoint
        {
            get { return _endPoint; }
            set { _endPoint = value; OnPropertyChanged("Endpoint"); }
        }

        private bool _isSelected;

        public bool IsSelected
        {
            get { return _isSelected; }
            set { _isSelected = value; OnPropertyChanged("IsSelected"); }
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文