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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With