【发布时间】:2019-11-13 23:49:10
【问题描述】:
这快把我逼疯了。几个小时以来我一直在寻找问题的根源,但我开始怀疑这不是我的逻辑问题......也许我错了。
问题描述
我有一个简单的条目。它的 Text 属性绑定到 ViewModel 中类型为 double 的属性。同时我订阅了Unfocused Event,它的 EventHandler 只是将entry.Text 属性设置为"1.0"(实际上我可以重现 x.y0 的问题,即任何最后一位为 0 的小数)。如果现在我在 Entry 中写入任何内容(“1”或“1.”或“1.0”!!!)并离开 Entry(通过点击外部或录音on Done)以便Unfocused 被触发,App 变得无响应。
注意:我知道在事件处理程序中设置entry.Text = 1.0 听起来有点奇怪。事实是,我通过尝试格式化 entry.Text 值遇到了这个问题,如下所示。
if (double.TryParse(entry.Text, out double result))
{
entry.Text = String.Format("{0:F2}", result);
}
String.Format 尝试将小数点四舍五入到小数点后两位。如果我给6.999 预期值应该是7.00,但应用程序 变得无响应。
重现问题的步骤
- 创建空白 Xamarin.Forms 项目。
- 删除 MainPage.xaml 文件中的默认 Label 以包含以下 Entry,改为:
<StackLayout>
<Entry Text="{Binding Weight}"
Unfocused="entry_Unfocused"/>
</StackLayout>
- 在后面的代码中添加如下EventHandler,并设置页面的
BindingContext属性如下:
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";
}
}
- 像这样创建 ViewModel:
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));
}
}
- 运行应用程序并在Entry中输入任何内容。
- 离开 Entry 以便
Unfocused被解雇。
我的系统配置:
- Visual Studio v. 16.3.8
- Xamarin.Forms 4.2.0.709249
- Android 8
谁能解释这里发生了什么,无论如何要解决这个问题?
【问题讨论】:
-
我假设 Unfocus 事件在无限循环中被调用。这应该很容易验证
-
@Deczaloth 在最新版本的 X.Forms (4.4) 和 Android 9 中也会发生同样的事情。
标签: c# xamarin.forms xamarin.android double string.format