Обычно вы сосредотачиваетесь на моделях данных, а не на элементах управления. Вы связываете состояние элементов управления с соответствующей моделью данных. Затем используйте 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>