1
votes

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>
1
Is IsChecked actually a Dependency Property or a property that is triggering the PropertyChanged event? That looks fine to me so I would double check the binding itself. - TyCobb
IsChecked is just a standard property i.e. not a Dependency Property. Should it be? - user3124134
It doesn't have to be, but you need to make sure you are firing the PropertyChanged Event in the setter. If you don't, there's nothing to tell the Binding that the value changed. Here's a page for DependencyProperty codeproject.com/Articles/18270/… and for binding to a business object property, look into the INotifyPropertyChanged interface and WPF. - TyCobb
The problem you mentioned here is occurred only when the PropertyChanged event not fired properly on setting the value to IsChecked property. Check again the property changed event fired properly with proper values. - Boopesh

1 Answers

1
votes

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