正如第一个答案中所正确提到的,设置键盘标志位不能直接完成。虽然您可以创建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;
}
}
然后在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>
TargetType
,还是必须为每个Entry
元素设置这些属性? - JKennedy