Как выделить все строки в сетке данных с помощью флажка (wpf)? - PullRequest
0 голосов
/ 04 апреля 2020

Я пытаюсь выбрать все строки в сетке данных с помощью флажка, используя этот код, когда я проверяю флажок, все строки выбраны, но без галочки.

Это мой столбец 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>

Спасибо за помощь

1 Ответ

0 голосов
/ 04 апреля 2020

Обычно вы сосредотачиваетесь на моделях данных, а не на элементах управления. Вы связываете состояние элементов управления с соответствующей моделью данных. Затем используйте ICommand для запуска изменения данных.

RelayCommand.cs
Реализация взята из Документы Microsoft: Шаблоны - Приложения WPF с дизайном Model-View-ViewModel Шаблон - ретрансляция команды Logi c

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>
...