Hello,
Welcome to our Microsoft Q&A platform!
When you use the entry behavior like the following code, TextChanged event loops round, the text will always be "1".
using System;
using Xamarin.Forms;
namespace WorkingWithBehaviors
{
public class NumericValidationBehavior : Behavior<Entry>
{
protected override void OnAttachedTo (Entry entry)
{
entry.Completed += OnEntryTextCompleted;
//entry.TextChanged += OnEntryTextChanged;
base.OnAttachedTo (entry);
}
protected override void OnDetachingFrom (Entry entry)
{
entry.Completed -= OnEntryTextCompleted;
//entry.TextChanged -= OnEntryTextChanged;
base.OnDetachingFrom (entry);
}
private void OnEntryTextCompleted(object sender, EventArgs e)
{
double result = double.Parse(((Entry)sender).Text);
((Entry)sender).Text = result > 17 ? (result > 28 ? "3" : "2") : "1";
}
void OnEntryTextChanged (object sender, TextChangedEventArgs args)
{
double result = double.Parse(args.NewTextValue);
((Entry)sender).Text = result >17? (result > 28?"3": "2") : "1";
}
}
}
So, you could have a try to use MVVM, ProcessYear
method is the key to conver text.
ViewModel
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
namespace EntryBehaviorDemo
{
class viewModel: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string year;
public string Year { get { return year; } set { if (year != value) { year = ProcessYear(value); OnPropertyChanged(); } } }
private string ProcessYear(string year_)
{
if (string.IsNullOrEmpty(year_))
return year_;
double result = double.Parse(year_);
year_ = result > 17 ? (result > 28 ? "3" : "2") : "1";
return year_;
}
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
BindingContext
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new viewModel();
}
}
XAML
<StackLayout>
<Entry Placeholder="enter number" Text="{Binding Year, Mode=TwoWay}"></Entry>
</StackLayout>
Best Regards,
Wenyan Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.