Search code examples
wpfxamleventswpfdatagrid

How to unsubscribe from Check/Uncheck event of datagridcheckbox column in WPF?


I subscribed to the Check/Uncheck event via cell style, like below.

   <DataGridCheckBoxColumn  x:Name="colAccept" Binding="{Binding Accepted}" Header="Accepted">
       <DataGridCheckBoxColumn.CellStyle>
          <Style>
             <EventSetter Event="CheckBox.Checked" Handler="OnChecked_Accepted"/>
             <EventSetter Event="CheckBox.Unchecked" Handler="OnUnchecked_Accepted"/>
          </Style>
        </DataGridCheckBoxColumn.CellStyle>
   </DataGridCheckBoxColumn>

I am updating the property that is bound to this column from the code behind but would not like the event to fire that one time. In winforms, I would unsubscribe from the event, then uncheck the checkbox, and then resubscribe, but how could I do this in WPF xaml?


Solution

  • Its easier to use a DataGridTemplateColumn instead.

            <DataGridTemplateColumn Header="Accepted">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox IsChecked="{Binding Mode=OneWay}" Checked="OnChecked_Accepted" Unchecked="OnUnchecked_Accepted" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
    

    in the handler

        private void OnUnchecked_Accepted(object sender, RoutedEventArgs e)
        {
            var cb = sender as CheckBox;
            cb.Unchecked -= OnUnchecked_Accepted;  //this line unsubscribes the event
        }