是否可以将键盘设置为" Sentence Capitalization"在XAML中输入?

时间:2016-06-13 09:07:56

标签: c# xaml xamarin xamarin.forms

我在看Xamarin.Forms: Specifying additional keyboard options

并且看到了将键盘标记设置为" Sentence Capitalization"

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

这看起来不错,我想在XAML中使用它。

这可以在XAML中完成吗?

2 个答案:

答案 0 :(得分:8)

正如第一个答案中正确提到的那样,开箱即用的设置键盘标志是不可能的。虽然你可以肯定是Entry的子类,但通过创建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;
        }
    }

然后在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>

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

<Style TargetType="Entry">
    <Setter Property="local:KeyboardStyle.KeyboardFlags"
            Value="Spellcheck,CapitalizeSentence"/>
</Style>

答案 1 :(得分:1)

到现在为止 ,无法在XAML中执行此操作。

您必须以编程方式执行此操作。

有关KeyboardFlags的更多信息。

作为建议,您可以扩展Entry和该属性。