Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is It possible to set a Keyboard to "Sentence Capitalisation" in XAML for an Entry?

I was looking at Xamarin.Forms: Specifying additional keyboard options

And saw this peice of code to Setting a Keyboard flag to "Sentence Capitalisation"

Content = new StackLayout
{
    Padding = new Thickness(0, 20, 0, 0),
    Children =
    {
        new Entry
        {
          Keyboard = Keyboard.Create(KeyboardFlags.CapitalizeSentence)
        }
    }
};

This looks great and I would like to use it in XAML.

Is this possible to do in XAML?

like image 231
User1 Avatar asked Jan 06 '23 22:01

User1


1 Answers

As mentioned correctly in the first answer, setting the keyboard flags is not possible out of the box. While you can certainly subclass Entry, there is a more elegant way by creating an attached property:

public class KeyboardStyle
    {
        public static BindableProperty KeyboardFlagsProperty = BindableProperty.CreateAttached(
            propertyName: "KeyboardFlags",
            returnType: typeof(string),
            declaringType: typeof(InputView),
            defaultValue: null,
            defaultBindingMode: BindingMode.OneWay,
            propertyChanged: HandleKeyboardFlagsChanged);

        public static void HandleKeyboardFlagsChanged(BindableObject obj, object oldValue, object newValue)
        {
            var entry = obj as InputView;

            if(entry == null)
            {
                return;
            }

            if(newValue == null)
            {
                return;
            }

            string[] flagNames = ((string)newValue).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            KeyboardFlags allFlags = 0;

            foreach (var flagName in flagNames) {
                KeyboardFlags flags = 0;
                Enum.TryParse<KeyboardFlags>(flagName.Trim(), out flags);
                if(flags != 0)
                {
                    allFlags |= flags;      
                }
            }

            Debug.WriteLine("Setting keyboard to: " + allFlags);
            var keyboard = Keyboard.Create(allFlags);

            entry.Keyboard = keyboard;
        }
    }

Then use it from within XAML (don't forget to add the local namespace):

<?xml version="1.0" encoding="utf-8"?>
<ContentPage
        xmlns="http://xamarin.com/schemas/2014/forms"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        xmlns:local="clr-namespace:KeyboardTest"
        x:Class="KeyboardTest.KeyboardTestPage">

    <Entry x:Name="entry" Text="Hello Keyboard" local:KeyboardStyle.KeyboardFlags="Spellcheck,CapitalizeSentence"/>
</ContentPage>

You can also use this as part of a blanket style like so:

<Style TargetType="Entry">
    <Setter Property="local:KeyboardStyle.KeyboardFlags"
            Value="Spellcheck,CapitalizeSentence"/>
</Style>
like image 94
Krumelur Avatar answered Jan 08 '23 10:01

Krumelur