1+ using System ;
2+ using System . ComponentModel ;
3+ using System . Globalization ;
4+
5+ namespace Microsoft . Maui . Converters ;
6+
7+ public sealed class GridLengthTypeConverter : TypeConverter
8+ {
9+ public override bool CanConvertFrom ( ITypeDescriptorContext ? context , Type ? sourceType )
10+ => sourceType == typeof ( double ) || sourceType == typeof ( string ) ;
11+
12+ public override object ConvertFrom ( ITypeDescriptorContext ? context , CultureInfo ? culture , object ? value )
13+ => value switch
14+ {
15+ double d => ( GridLength ) d ,
16+ string strValue => strValue . Trim ( ) . ToLowerInvariant ( ) switch
17+ {
18+ "auto" => GridLength . Auto ,
19+ "*" => new GridLength ( 1 , GridUnitType . Star ) ,
20+ #pragma warning disable CA1846 , CA1865
21+ _ when strValue . EndsWith ( "*" , StringComparison . Ordinal ) && double . TryParse ( strValue . Substring ( 0 , strValue . Length - 1 ) , NumberStyles . Number , CultureInfo . InvariantCulture , out var length ) => new GridLength ( length , GridUnitType . Star ) ,
22+ #pragma warning restore CA1846 , CA1865
23+ _ when double . TryParse ( strValue , NumberStyles . Number , CultureInfo . InvariantCulture , out var length ) => new GridLength ( length ) ,
24+ _ => throw new FormatException ( ) ,
25+ } ,
26+ _ => throw new NotSupportedException ( ) ,
27+ } ;
28+
29+ public override bool CanConvertTo ( ITypeDescriptorContext ? context , Type ? destinationType ) => destinationType == typeof ( string ) ;
30+ public override object ConvertTo ( ITypeDescriptorContext ? context , CultureInfo ? culture , object ? value , Type ? destinationType )
31+ {
32+ if ( destinationType == typeof ( string ) && value is GridLength length )
33+ {
34+ if ( length . IsAuto )
35+ return "auto" ;
36+ if ( length . IsStar )
37+ return $ "{ length . Value . ToString ( CultureInfo . InvariantCulture ) } *";
38+ return $ "{ length . Value . ToString ( CultureInfo . InvariantCulture ) } ";
39+ }
40+ throw new NotSupportedException ( $ "Cannot convert { value ? . GetType ( ) } to { destinationType } ") ;
41+
42+ }
43+ }
0 commit comments