【发布时间】:2015-01-13 23:51:08
【问题描述】:
我有一个 PCL,它将我的 MVVM 页面存储在 XAML 中。我在 XAML 文件中有以下内容,但我想禁用键盘上的自动完成功能。有谁知道我如何在 XAML 中做到这一点?
<Entry Text="{Binding Code}" Placeholder="Code" />
【问题讨论】:
标签: xaml mvvm portable-class-library xamarin.forms
我有一个 PCL,它将我的 MVVM 页面存储在 XAML 中。我在 XAML 文件中有以下内容,但我想禁用键盘上的自动完成功能。有谁知道我如何在 XAML 中做到这一点?
<Entry Text="{Binding Code}" Placeholder="Code" />
【问题讨论】:
标签: xaml mvvm portable-class-library xamarin.forms
自定义Keyboard 实例可以使用x:FactoryMethod 属性在XAML 中创建。您想要的可以通过以下标记实现:
<Entry Text="{Binding Code}" Placeholder="Code">
<Entry.Keyboard>
<Keyboard x:FactoryMethod="Create">
<x:Arguments>
<KeyboardFlags>None</KeyboardFlags>
</x:Arguments>
</Keyboard>
</Entry.Keyboard>
</Entry>
KeyboardFlags.None 从该字段中删除所有特殊键盘功能。
Multiple enums 可以在 XAML 中通过用逗号分隔来指定:
<KeyboardFlags>CapitalizeSentence,Spellcheck</KeyboardFlags>
当您不需要自定义Keyboard 时,可以利用x:Static 属性来使用one of the predefined ones:
<Entry Placeholder="Phone" Keyboard="{x:Static Keyboard.Telephone}" />
【讨论】:
虽然已经有了答案,但我想我会进一步详细说明 XAML 中的用法。
与代码隐藏不同,您不能创建要使用的 Keyboard 类的新实例,但有一种方法。希望您已经对您的 App.cs 进行了 xaml 化(删除它,并创建 App.xaml 和 App.xaml.cs),这样您就不必检查 Resources 属性是否已初始化。
下一步是重写 OnStart() 方法,并为您使用的各种键盘添加正确的条目。我通常使用三个键盘:数字、电子邮件和文本。另一个有用的是 Url 键盘,但您可以以相同的方式添加它。
protected override void OnStart()
{
base.OnStart();
this.Resources.Add("KeyboardEmail", Keyboard.Email);
this.Resources.Add("KeyboardText", Keyboard.Text);
this.Resources.Add("KeyboardNumeric", Keyboard.Numeric);
}
这个小代码将使键盘作为静态资源可用。要在 XAML 中使用它们,只需执行以下操作:
<Entry x:Name="emailEntry" Text="{Binding EMail}" Keyboard="{StaticResource KeyboardEmail}" />
瞧,您的条目现在有一个电子邮件键盘。
【讨论】:
x:Static 属性的详细信息,请参阅我的答案。
Forms 支持 KeyboardFlags.Suggestion 枚举,我认为它旨在控制这种行为,但它似乎没有很好的文档记录。
【讨论】:
None 成员。 github.com/xamarin/Xamarin.Forms/blob/…
KeyboardFlags 应该这样做,例如:
MyEntry.Keyboard = Keyboard.Create(KeyboardFlags.CapitalizeSentence | KeyboardFlags.Spellcheck);
【讨论】:
我知道这是一个旧线程,但我找到了一种在样式中执行此操作的方法。
我的所有样式都在我的ResourceDictionary 中定义在我的App.xaml 中。在那里我可以做以下事情:
<Style x:Key="StyleEntryNumeric" TargetType="Entry">
<Setter Property="ClearButtonVisibility" Value="WhileEditing" />
<Setter Property="Keyboard" Value="Numeric" />
</Style>
然后像这样使用它:
<Entry Style="{DynamicResource StyleEntryNumeric}" />
但是,如果我想设置KeyboardFlags 怎么办?好吧,我用我的App.xaml.cs 中的一些代码和一个简单的绑定来做到这一点。首先,在我的顶部App.xaml:
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Name="ThisControl"
x:Class="App.Forms.App">
那我的样式在哪里都一样App.xaml:
<Style x:Key="StyleEntryText" TargetType="Entry">
<Setter Property="ClearButtonVisibility" Value="WhileEditing" />
<Setter Property="Keyboard" Value="{Binding Source={x:Reference ThisControl}, Path=KeyboardText}" />
</Style>
最后,在我的App.xaml.cs 代码后面:
public Keyboard KeyboardText
=> Keyboard.Create(KeyboardFlags.CapitalizeNone | KeyboardFlags.Spellcheck);
而且,如果需要,我可以在后面的代码中创建其他类似的属性以用于其他样式。
【讨论】: