Reputation: 85
I'm still very new to WPF/XAML so bear with me here...
I have a DataGrid that contains three columns: 2 DataGridTextColumns and a DataGridTemplateColumn, which contains a CheckBox. The DataGrid is bound to a collection that displays objects of type Field. The IsChecked property of the CheckBox is also bound to a property in a ViewModel.
What I'd like to be able to achieve is that when a Field i.e. a row in the DataGrid is clicked, the Field's corresponding CheckBox becomes checked or unchecked.
I have bound to the SelectedItem of the DataGrid and can retrieve the Field that's clicked. I then set the "IsChecked" property of the Field accordingly.
However, the check in the CheckBox does not appear (or disappear) seemingly until the row in the DataGrid is repainted. That is, if I scroll down so that the row disappears out of view and then scroll back up to it, the check is displayed in the CheckBox. I am raising an INotifyPropertyChanged event when the IsChecked property value is set.
Would anyone be able to suggest what might be going wrong here?
The code for the column containing the CheckBox is shown below.
Any ideas/suggestions/help would be greatly appreciated.
Many thanks.
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="5" />
</DataTemplate>
</DataGridTemplateColumn>
</DataGridTemplateColumn>
Upvotes: 1
Views: 1380
Reputation: 26268
Try this:
First define new DataGridRow style to subscribe PreviewMouseButtonDownEvent:
<Style TargetType="{x:Type DataGridRow}">
<EventSetter Event="PreviewMouseLeftButtonDown"
HandledEventsToo="True"
Handler="PreviewDataGridRowClick"
></EventSetter>
</Style>
And eventhandler:
private void PreviewDataGridRowClick(object sender, MouseButtonEventArgs e)
{
var datagridRow = (DataGridRow) sender;
var underlyingVm = datagridRow.Item as YourVM;
underlyingVm.IsChecked = !underlyingVm.IsChecked;
e.Handled = true;
}
Upvotes: 1