0

im trying to select all rows in datagrid with checkbox using this code, when i check the checkbox all rows are selected but without the tick marK.

This is my xaml column

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

Code behind

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

This is the style

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

Thanks for help

1 Answers1

0

Usually you focus on the data models and not on the controls. You bind the controls' state to the corresponding data model. Then use ICommand to trigger the data modification.

RelayCommand.cs
Implementation taken from 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>
BionicCode
  • 1
  • 4
  • 28
  • 44