DataGridTemplateColumn with CheckBox

1.1k views Asked by At

I have a dynamic DataGrid in which one of the columns is a CheckBox. I created a "Transactions" class in which I bind the columns of the datagrid to different properties in that class. I want my checkbox to be binded to a Property which is an integer. It is an integer because I am populating the properties from a query on to my database. The possible integers are either 1 (True) or 0 (False). Here is what I have so far to create my Database:

    private DataGridTemplateColumn GetVoidColumn()
    {
        DataGridTemplateColumn voidColumn = new DataGridTemplateColumn();
        voidColumn.Header = "Void";

        Binding bind = new Binding("Visible");
        bind.Mode = BindingMode.TwoWay;

        // Create the CheckBox
        FrameworkElementFactory voidFactory = new FrameworkElementFactory(typeof(CheckBox));
        voidFactory.SetValue(CheckBox.IsCheckedProperty, bind);
        DataTemplate voidTemplate = new DataTemplate();
        voidTemplate.VisualTree = voidFactory;

        voidColumn.CellTemplate = voidTemplate;

        return voidColumn;
    }

On my actual Datagrid, the CheckBox shows up but they are always Unchecked, even if the property is showing a 1. Even when I do my row validation, the value that shows up for the column is correct, contains a 1 or a 0 in the ItemArray of the row. Its just that the checkbox isn't being checked in the UI for some reason. Can someone help me out with this?

1

There are 1 answers

0
Haris Hasan On BEST ANSWER

You can use Converters to convert property value 0 and 1 to false and true. Probably the IsChecked property is not understanding value 0 and 1. Create a class that implements IValueConverter and apply that converter to convert int to bool.

Another option could be to create a property for this in your class

public bool IsChecked
{
   get
   {
       if(IntProperty == 0)
          return false;
       return true;
   }
   set
   {
       if(value)
          IntProperty = 1;
       else 
          IntProperty = 0;
   }
}

now instead of binding with int property bind with property above