I have a ready-made project in which I added a checkbox column, now I want to click on the header to select all the checkbox.
for example, I used this code https://stackoverflow.com/a/48990131/11732842
DataGrid is populated through AutoGeneratingColumn
private void MainDG_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
Wpf.DGSetDateFormat(e);
if (e.Column is DataGridCheckBoxColumn && e.Column.Header.ToString()== "IsCheced")
{
var checkboxFactory = new FrameworkElementFactory(typeof(CheckBox));
checkboxFactory.SetValue(FrameworkElement.HorizontalAlignmentProperty, HorizontalAlignment.Center);
checkboxFactory.SetValue(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Center);
checkboxFactory.SetBinding(ToggleButton.IsCheckedProperty, new Binding(e.PropertyName) { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Path = ViewModel.AllSelected });
e.Column = new DataGridTemplateColumn
{
Header = e.Column.Header,
CellTemplate = new DataTemplate { VisualTree = checkboxFactory },
SortMemberPath = e.Column.SortMemberPath
};
}
}
error Path = ViewModel.AllSelected: failed to explicitly convert the bool type to path
You are supposed to set the Path
property to an actual binding path, or not set it all since you pass a path to the constructor when you create the binding:
checkboxFactory.SetBinding(ToggleButton.IsCheckedProperty,
new Binding(e.PropertyName) { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });
The CheckBox
in the "IsCheced" column should bind to the IsCheced
(did you misspell "checked") property. The CheckBox
in the header should bind to the property of the view model:
checkboxHeaderFactory.SetBinding(ToggleButton.IsCheckedProperty,
new Binding(nameof(ViewModel.AllSelected))
{
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
Source = DataContext
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.