使用 MaxLength 属性创建自定义 Entry 控件
Xamarin Forms Entry
控件没有 MaxLength
属性。为此,你可以通过添加 Bindable MaxLength
属性来扩展 Entry
,如下所示。然后你只需要在 Entry
上订阅 TextChanged
事件并在调用时验证 Text
的长度:
class CustomEntry : Entry
{
public CustomEntry()
{
base.TextChanged += Validate;
}
public static readonly BindableProperty MaxLengthProperty = BindableProperty.Create(nameof(MaxLength), typeof(int), typeof(CustomEntry), 0);
public int MaxLength
{
get { return (int)GetValue(MaxLengthProperty); }
set { SetValue(MaxLengthProperty, value); }
}
public void Validate(object sender, TextChangedEventArgs args)
{
var e = sender as Entry;
var val = e?.Text;
if (string.IsNullOrEmpty(val))
return;
if (MaxLength > 0 && val.Length > MaxLength)
val = val.Remove(val.Length - 1);
e.Text = val;
}
}
在 XAML 中的用法:
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:customControls="clr-namespace:CustomControls;assembly=CustomControls"
x:Class="Views.TestView">
<ContentView.Content>
<customControls:CustomEntry MaxLength="10" />
</ContentView.Content>