This is driving me crazy. I have been looking for the source of the issue for hours, but i am starting to suspect this is not an issue in my logic... Maybe i am wrong.
I have a simple Entry. Its Text property is bound to a property with type double in a ViewModel. At the same time i subscribe to the Unfocused
Event whose EventHandler simply sets the entry.Text
property to "1.0"
(actually i can reproduce the issue for x.y0, that is any decimal whose final digit is 0). If now i write in the Entry anything (except "1" or "1." or "1.0"!!!) and leave the Entry (by tapping outside or taping on Done) so that Unfocused
is fired, the App becomes unresponsive.
Note: I know that it sounds a bit strange to set entry.Text = 1.0
in the event handler. The truth is that i came across this issue by trying to format the entry.Text
value as follows.
if (double.TryParse(entry.Text, out double result))
{
entry.Text = String.Format("{0:F2}", result);
}
There String.Format
tries to round the decimal to two decimals. If i give 6.999
the expected value should be 7.00
, but the App becomes unresponsive instead.
<StackLayout>
<Entry Text="{Binding Weight}"
Unfocused="entry_Unfocused"/>
</StackLayout>
BindingContext
property of the page as follows:public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
BindingContext = new viewmodel();
}
private void entry_Unfocused(object sender, FocusEventArgs e)
{
((Entry)sender).Text = "1.0";
}
}
public class viewmodel : INotifyPropertyChanged
{
public viewmodel()
{
}
private double _Weight;
public double Weight
{
get => _Weight;
set
{
if (_Weight != value)
{
_Weight = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Unfocused
is fired.Could anyone explain what is going on here, and anyway to work around this issue?
i test your codes,and debug it,i found it would infinite loop in
set
{
if (_Weight != value)
{
_Weight = value;
OnPropertyChanged();
}
}
}
i think it bescause your Weight
property is double
type,it could not set it as string
correctly,you could try to define the Weight as string.
private string _Weight;
public string Weight
{
get => _Weight;
set
{
if (_Weight != value)
{
_Weight = value;
OnPropertyChanged();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With