Search code examples
wpfuser-controlswpf-controlswpfdatagrid

checkboxcolumn not able to persist its checked status when convertback is used in wpf


I have a datagrid to which i am adding a checkboxcolumn programmatically. To this column I have an enum which needs to be bound but since checkboxcolumn will take only bool value, i am using a converter. I also need to update my source when my target checkbox changes. Although my code is updating my source when I check the checkbox but as soon as I lose focus the checked (tick) goes away. How can I make the check of the checkbox keep persistant?

I tried other UpdateSourceTrigger values but it is not working.

The following is the code of checkboxcolumn

        Binding binding = new Binding("GridCRUDStatus") { Converter = new CheckBoxColConverter(), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.Explicit };
        DataGridCheckBoxColumn chkCol = new DataGridCheckBoxColumn() { Header = "Select", Binding = binding };

The converter class

internal class CheckBoxColConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        GridCRUDStatus status;
        if (Enum.TryParse<GridCRUDStatus>(value.ToString(), out status))
        {
            if (status == GridCRUDStatus.Selected)
                return true;
        }

        return false;
        //throw new NotImplementedException();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        bool chkValue;
        if (Boolean.TryParse(value.ToString(), out chkValue))
        {
            if (chkValue)
                return GridCRUDStatus.Delete;
        }
        return GridCRUDStatus.Read;

        //return null;
    }

    #endregion
}

I tried searching on the net but not able to find a solution. Please let me know if you need any further info from my end.

Please help! Thanks in advance.

Regards,

Samar


Solution

  • I got the solution to my problem. In the "Convert" method I was checking if GridCRUDStatus is Selected then return true and in "ConvertBack" method I was checking if value is true then return GridCRUDStatus.Delete, this was calling the "Convert" method again and returning false again which was unchecking the checkbox.

    Regards,

    Dhaval S