是否可以在XAML中为键入设置键盘为"句子大写"?

use*_*er1 4 c# xaml xamarin xamarin.forms

我在看Xamarin.Forms:指定其他键盘选项

并看到了将键盘标志设置为"Sentence Capitalization"的代码

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

这看起来很棒,我想在XAML中使用它.

这可以在XAML中做到吗?

Kru*_*lur 8

正如在第一个答案中正确提到的那样,开箱即用的设置键盘标志是不可能的.虽然你可以肯定是子类Entry,但通过创建附加属性有一种更优雅的方式:

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后在XAML中使用它(不要忘记添加local命名空间):

<?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>
Run Code Online (Sandbox Code Playgroud)

您也可以将此作为毯子样式的一部分,如下所示:

<Style TargetType="Entry">
    <Setter Property="local:KeyboardStyle.KeyboardFlags"
            Value="Spellcheck,CapitalizeSentence"/>
</Style>
Run Code Online (Sandbox Code Playgroud)