Search code examples
c#wpfxamlgridviewcolumnxaml-binding

How to set width=auto on GridViewColumn through Bindings?


I need to set the width of my GridViewColumn to either a value, or auto, depending on a boolean. I currently have this set-up:

<GridViewColumn Width="{Binding ColumnWidth}">
public string DepotAssignmentWidth { get { return (hasBoolean) ? "50" : "auto"; } }

This has the desired behaviour, but gives me parsing errors:

System.Windows.Data Error: 6 : 'SystemConvertConverter' converter failed to convert value 'auto' (type 'String'); fallback value will be used, if available. BindingExpression:Path=Removed; DataItem='Removed' (HashCode=15576908); target element is 'GridViewColumn' (HashCode=46088874); target property is 'Width' (type 'Double') FormatException:'System.FormatException: Input string was not in a correct format.
   at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
   at System.String.System.IConvertible.ToDouble(IFormatProvider provider)
   at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
   at MS.Internal.Data.SystemConvertConverter.Convert(Object o, Type type, Object parameter, CultureInfo culture)
   at System.Windows.Data.BindingExpression.ConvertHelper(IValueConverter converter, Object value, Type targetType, Object parameter, CultureInfo culture)'

I've also tried this, which gives doesn't work either:

public GridLength DepotAssignmentWidth { get { return (hasBoolean) ? new GridLength(50, GridUnitType.Pixel) : GridLength.Auto; } }
System.Windows.Data Error: 1 : Cannot create default converter to perform 'one-way' conversions between types 'System.Windows.GridLength' and 'System.Double'. Consider using Converter property of Binding. BindingExpression:Path=DepotAssignmentWidth; DataItem='RoutesAndDepotsPresenter' (HashCode=39457967); target element is 'GridViewColumn' (HashCode=30364822); target property is 'Width' (type 'Double')  
System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='50' BindingExpression:Path=DepotAssignmentWidth; DataItem='RoutesAndDepotsPresenter' (HashCode=39457967); target element is 'GridViewColumn' (HashCode=30364822); target property is 'Width' (type 'Double')

And this, which gives me no errors, but doesn't seem to work.

public double DepotAssignmentWidth { get { return (hasBoolean) ? 50 : GridLength.Auto.Value; } }

What's the correct method of implementing this?


Solution

  • Try this:

    public double DepotAssignmentWidth 
    { 
        get 
        { 
            return (hasBoolean) ? 50 : double.NaN; 
        }
    }