【问题标题】:How to Select all rows in datagrid with checkbox (wpf)?如何使用复选框(wpf)选择数据网格中的所有行?
【发布时间】:2020-07-16 18:06:59
【问题描述】:

我尝试使用此代码选择带有复选框的数据网格中的所有行,当我选中复选框时,所有行都被选中但没有刻度线。

这是我的 xaml 专栏

 <DataGridTemplateColumn>
                            <DataGridTemplateColumn.Header>
                                <CheckBox Checked="chkSelectAll_Checked" Unchecked="chkSelectAll_Unchecked" Style="{StaticResource NVStyleCheckBoxAssistant}"></CheckBox>
                            </DataGridTemplateColumn.Header>
                            <DataGridTemplateColumn.CellTemplate >
                                <DataTemplate>
                                    <CheckBox IsChecked="{Binding Association_Click}" Style="{StaticResource NVStyleCheckBoxAssistant}"/>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
 </DataGridTemplateColumn>

后面的代码

 Private Sub chkSelectAll_Checked(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Association_Click(sender, e)
        dgv1.SelectAll()
 End Sub

这就是风格

 <Style x:Key="NVStyleCheckBoxAssistant"  TargetType="{x:Type CheckBox}">
    <Setter Property="VerticalAlignment" Value="center"/>
    <Setter Property="HorizontalAlignment" Value="center"/>
    <Setter Property="IsChecked"  Value="{Binding EstSelectionner, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type CheckBox}">
                <BulletDecorator Background="Transparent"    SnapsToDevicePixels="true">
                    <BulletDecorator.Bullet>
                        <Border BorderBrush="#D4D3D3" BorderThickness="2"   Background="White"  Width="14" Height="14" >
                            <Grid>
                                    <Rectangle Name="TickMark" Width="6" Height="6" Fill="#791937" Stroke="#791937" 
                                     Canvas.Top="2.5" Canvas.Left="2.5" StrokeThickness="1" Visibility="Hidden" />
                            </Grid>
                        </Border>
                    </BulletDecorator.Bullet>
                    <ContentPresenter Name="cnt" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                  RecognizesAccessKey="True"
                                  SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                  VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="5,0,0,0"/>
                </BulletDecorator>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter TargetName="TickMark" Property="Visibility" Value="Visible" />
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter TargetName="TickMark" Property="Opacity" Value="0.5" />
                        <Setter TargetName="cnt" Property="Opacity" Value="0.5"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

感谢帮助

【问题讨论】:

    标签: .net wpf vb.net checkbox selectall


    【解决方案1】:

    通常您专注于数据模型而不是控件。您将控件的状态绑定到相应的数据模型。然后使用ICommand触发数据修改。

    RelayCommand.cs
    实现取自Microsoft Docs: Patterns - WPF Apps With The Model-View-ViewModel Design Pattern - Relaying Command Logic

    public class RelayCommand : ICommand
    {
        #region Fields 
        readonly Action<object> _execute;
        readonly Predicate<object> _canExecute;
        #endregion // Fields 
        #region Constructors 
        public RelayCommand(Action<object> execute) : this(execute, null) { }
        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            _execute = execute; _canExecute = canExecute;
        }
        #endregion // Constructors 
        #region ICommand Members 
        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        public void Execute(object parameter) { _execute(parameter); }
        #endregion // ICommand Members 
    }
    

    TableData.cs

    public class TableData : INotifyPropertyChanged
    {
      public TableData(int value)
      {
        this.Value = value;
      }
    
      private bool isEnabled;   
      public bool IsEnabled
      {
        get => this.isEnabled;
        set 
        { 
          this.isEnabled = value; 
          OnPropertyChanged();
        }
      }
    
      private int value;
      public int Value
      {
        get => this.value;
        set
        {
          this.value = value;
          OnPropertyChanged();
        }
      }
    
      public event PropertyChangedEventHandler PropertyChanged;
    
      [NotifyPropertyChangedInvocator]
      protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
      {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
      }
    }
    

    ViewModel.cs

    class ViewModel
    {
      public ICommand SelectAllCommand 
      { 
        get => new RelayCommand(
          isChecked => this.TableDatas
            .ToList()
            .ForEach(tableData => tableData.IsEnabled = (bool) isChecked), 
          isChecked => isChecked is bool); 
      }
    
      public ObservableCollection<TableData> TableDatas { get; set; }
    
      public ViewModel()
      {
        this.TableDatas = new ObservableCollection<TableData>()
        {
          new  TableData(01234),
          new  TableData(56789),
          new  TableData(98765)
        };
      }
    }
    

    MainWindow.xaml

    <Window>
      <Window.DataContext>
        <ViewModel />
      </Window.DataContext>
    
      <DataGrid ItemsSource="{Binding TableDatas}"
                AutoGenerateColumns="False">
        <DataGrid.Columns>
          <DataGridCheckBoxColumn Binding="{Binding IsEnabled}">
            <DataGridCheckBoxColumn.Header>
              <CheckBox
                Command="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, 
                          Path=DataContext.SelectAllCommand}"
                CommandParameter="{Binding RelativeSource={RelativeSource Self}, 
                                   Path=IsChecked}" />
            </DataGridCheckBoxColumn.Header>
          </DataGridCheckBoxColumn>
          <DataGridTextColumn Header="Value" Binding="{Binding Value}" />
        </DataGrid.Columns>
      </DataGrid>
    </Window>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-31
      • 2015-03-28
      • 1970-01-01
      • 2012-01-02
      • 2011-03-12
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      相关资源
      最近更新 更多