Custom DataGridColumn Binding value

39 Views Asked by At

I am trying to create a custom DataGridColumn that simply shows a tick or cross icon depending on the Binding value, but the Binding value is always false

public class DataGridBoolColumn : DataGridBoundColumn
{
    private const double DATAGRIDBOOLCOLUMN_leftMargin = 12.0;
    private const double DATAGRIDBOOLCOLUMN_rightMargin = 12.0;

    public bool Value
    {
        get { return (bool)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Value.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(bool), typeof(DataGridBoolColumn), new PropertyMetadata(false));

    private FrameworkElement CreateIcon()
    {
        // Set Binding to ValueProperty
        BindingOperations.SetBinding(this, ValueProperty, Binding);

        PackIconMaterial icon = new PackIconMaterial();
        icon.Margin = new Thickness(DATAGRIDBOOLCOLUMN_leftMargin, 0.0, DATAGRIDBOOLCOLUMN_rightMargin, 0.0);
        icon.Height = 14.0;            

        // Determine if the icon should show Check or Cross based on Value
        if (Value)
        {
            icon.Foreground = new SolidColorBrush(new Color() { A = 255, R = 22, G = 100, B = 44 });
            icon.Kind = PackIconMaterialKind.Check;
        }
        else
        {
            icon.Foreground = new SolidColorBrush(new Color() { A = 255, R = 128, G = 16, B = 42 });
            icon.Kind = PackIconMaterialKind.Close;
        }

        return icon;
    }

    protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
    {
        return CreateIcon();
    }

    protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
    {
        return CreateIcon();
    }

}

Then in the XAML I bind the value

<DataGrid ItemsSource="{Binding Path=FilteredItems}">
    <local:DataGridBoolColumn Header="Trackable" Binding="{Binding Path=IsTrackable}" />
</DataGrid>

The Cross icon shows in the column, but the Value always returns False, which is not correct. It is not taking the Binding value.

There are no XAML binding errors.

How do I redirect the Binding to a custom dependency property?

0

There are 0 best solutions below