How to create a size property for a custom control. that is configurable in xaml?

GeorgeCookGeorgeCook PEUniversity ✭✭✭

here's my property:

    public static readonly BindableProperty ItemSizeProperty = BindableProperty.Create ("ItemSize", typeof(Size), typeof(GridView), new Size (100, 100), BindingMode.OneWay, null, null, null, null);

public Size ItemSize {
get {
return (Size)base.GetValue (GridView.ItemSizeProperty);
}
set {
base.SetValue (GridView.ItemSizeProperty, value);
}
}

Here's how I want to use it:
<xlabs:GridView x:Name="SpaceTemplatesGridView"
ItemSize="138,183"

however it say's can't convert from string to size.. how can I write a custom converter inside my control, so that I don't have to make the clients of my control do it constnatly

Answers

  • TommyBaggettTommyBaggett USUniversity ✭✭✭

    Hi George,

    You need to create a custom TypeConverter-derived class, as there isn't a stock one for the Size object. See the TypeConverter API docs for info and a list of the stock ones.

    First, add an attribute to your property like so:

    [TypeConverter (typeof(SizeTypeConverter))]
    public Size ItemSize {
        get {
            return (Size)base.GetValue (GridView.ItemSizeProperty);
        }
        set {
            base.SetValue (GridView.ItemSizeProperty, value);
        }
    }
    

    Next, create the TypeConverter-derived class and override CanConvertFrom and ConvertFrom.

    public class SizeTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(Type sourceType)
        {
            return sourceType == typeof(string);
        }
    
        public override object ConvertFrom(System.Globalization.CultureInfo culture, object value)
        {
            Size result = null;
    
            string sizeParams = value as string;
            if (sizeParams != null)
            {
                // Throw in some code here to parse the string and convert it to a Size object.
            }
    
            return result;
        }
    }
    

    That should do it. Hit me up if you run into any snags.

  • FredyWengerFredyWenger CHInsider ✭✭✭✭✭

    @GeorgeCook:
    This posting don't have anything to do with your problem but I see, that you have some problems to format your posting (code).
    I have wrote a .pdf that also include some tips how to format the forum-postings.
    Maybe you want to have a look at it? :smirk:
    Link: forums.xamarin.com/discussion/36821/quickstart-guide-to-start-developing-with-xamarin-forms#latest

Sign In or Register to comment.