0
データバインドされたエントリフィールドの長さを制限する動作を使用しようとしていますが、わかりません。データバインディングは、動作を使用しないときに機能します。この動作を使用してエントリの長さを制限しますが、データバインディングが壊れます。ここに私のコードは次のとおりです。XAMLでXamarinフォーム:データバインドされたエントリの長さを制限する
:
XAML.csで<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>
...
:
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;
}
}
}
私はあなたのコードを試して、それは私のために働く。私が持っている唯一の違いは、ページコンストラクタではなくXAMLにバインディングを置くことですが、それを自分のやり方に変更しても機能します。あなたのバインディングがうまくいかないことをどのように確認しましたか? –