如何通过Bindings在GridViewColumn上设置width = auto?

时间:2014-09-24 10:37:35

标签: c# wpf xaml gridviewcolumn xaml-binding

我需要将GridViewColumn的宽度设置为值或auto,具体取决于布尔值。我目前有这个设置:

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

这有所需的行为,但是给了我解析错误:

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)'

我也试过这个,这也没有起作用:

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')

而且,这不会给我带来任何错误,但似乎无法发挥作用。

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

实现此目的的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

试试这个:

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