Search code examples
wpfdata-bindingdatatrigger

WPF datagrid set Checkbox Column by null value


Its a simple task still I have not found a solution for it.

I have a list of Objets each holding 2 properties, a String and a byte[]. I am setting the list as an itemscource for my Datatgid. I created a textcolumn with a binding to the string property. Now I want to add a Checkboxcolumn, which should NOT be checked if the byte[] property is NULL, and should be checkt otherwise.

I have found no example for this so far, I guessed that this might be possible to do with a datatrigger but I cant even write somthing down without the compliler complaining.


Solution

  • You can use the databinding engine and bind the property directly to the checkbox. Of course, the checkbox is expecting a Nullable<bool>, so you'll have to use a IValueConverter to transform the byte[] array into a bool?:

    [ValueConversion(typeof(object), typeof(bool?)]
    public class IsNullConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value == null;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
    
    
    <CheckBox IsChecked="{Binding Path=MyByteArray,
                                  Converter={StaticResource MyConverter},
                                  Mode=OneWay}"
              IsEnabled="False" />
    

    Note, I marked the binding mode as OneWay and the checkbox as disabled (i.e. readonly) because with the scenario, it doesn't make sense to allow the user to make changes to the state of the checkbox.