Xamarin Forms:限制数据绑定条目的长度

Xamarin Forms: limit the length of an entry that is data bound

我正在尝试使用一种行为来限制也是数据绑定的输入字段的长度,但我无法弄清楚。当我不使用该行为时,数据绑定有效。使用该行为来限制条目长度是可行的,但它会破坏数据绑定。这是我的代码:

在XAML中:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
    x:Class="MyApp.UserInfoPage"  
    xmlns:behaviors="clr-namespace:MyApp.Behaviors">
    ...  
        <Entry x:Name="UserName" FontSize="Small" Keyboard="Text">
            <Entry.Behaviors>
                <behaviors:EntryLengthValidatorBehavior MaxLength="7"/>
            </Entry.Behaviors>
        </Entry>
    ...

在XAML.cs中:

public MyInfoPage(MyDataAdapter myDataAdapter)
{
    InitializeComponent();
    BindingContext = myDataAdapter;
    UserName.SetBinding(Entry.TextProperty, "UserName", BindingMode.TwoWay);
...

和EntryLengthValidatorBehavior.cs:

class EntryLengthValidatorBehavior : Behavior<Entry>
{
    public int MaxLength { get; set; }

    protected override void OnAttachedTo(Entry bindable)
    {
        base.OnAttachedTo(bindable);
        bindable.TextChanged += OnEntryTextChanged;
    }

    protected override void OnDetachingFrom(Entry bindable)
    {
        base.OnDetachingFrom(bindable);
        bindable.TextChanged -= OnEntryTextChanged;
    }

    private void OnEntryTextChanged(object sender, TextChangedEventArgs e)
    {
        var entry = (Entry)sender;

        if (entry.Text != null && entry.Text.Length > this.MaxLength)
        {
            string entryText = entry.Text;
            entry.TextChanged -= OnEntryTextChanged;
            entry.Text = e.OldTextValue;
            entry.TextChanged += OnEntryTextChanged;
        }
    }
}

要么我的调试会话中发生了某些事情,要么我脑子放了个屁,因为重新启动后一切正常 Visual Studio。抱歉造成混淆。