shuhelohelo’s blog

Xamarin.Forms多めです.

カスタムコントロールにバインダブルなFontSizeプロパティを設ける方法

forums.xamarin.com

LabelなどのFontSizeは数字でもLarge,SmallなどのNamedSize列挙体の値でもどちらでも大丈夫です.

ではそれをカスタムコントロールのプロパティでNamedSize列挙体を使うためにはどうしたらいいのか.

以下のようにする.

    //https://github.com/arun6202/XamarinFormsStarterKit/blob/750e211cd4dae3595406aba8e9f53dee1787adff/XamarinFormsStarterKit/XamarinFormsStarterKit/Xamarin.FormsBook.Toolkit/CheckBox.xaml.cs
        [Xamarin.Forms.TypeConverter(typeof(FontSizeConverter))]
        public double FontSize
        {
            get { return (double)GetValue(FontSizeProperty); }
            set { SetValue(FontSizeProperty, value); }
        }
        public static readonly BindableProperty FontSizeProperty = BindableProperty.Create(
                propertyName: nameof(FontSize),
                returnType: typeof(double),
                declaringType: typeof(Balloon),
                defaultValue: Device.GetNamedSize(NamedSize.Default,typeof(Label)),
                defaultBindingMode: BindingMode.TwoWay,
                propertyChanged: FontSizePropertyChanged
            );
        private static void FontSizePropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var control = (Balloon)bindable;
            var fontSize = (double)newValue;
            control.label.FontSize = fontSize;
        }

すると,このようにインテリセンスで候補が表示される.

f:id:shuhelohelo:20191228171026p:plain

数値でもOk.

Githubで検索すると上記のやり方が沢山でてくるので,きっと定番の方法なのだろう.

github.com

ソースコード

github.com