王彦为

聚沙成塔
  1. 首页
  2. WPF
  3. 正文

WPF中TextBox在.NET 4.5无法输入浮点数

2016-12-16 14527点热度 50人点赞 2条评论

最近发现一个很奇怪的现象,TextBox中的Text绑定double型数据,触发条件UpdateSourceTrigger=PropertyChanged时,在.net4.5框架下无法输入小数点,而在.net 4.0之前的框架不存在这个问题。为了描述地更清晰,下面做一个简单的模型来说明。

现象描述

// .xaml
<Grid>
    <TextBox Text="{Binding Score,UpdateSourceTrigger=Default}"/>
</Grid>

// .cs
using System.ComponentModel;
public partial class Window1 : Window
{
    Student stu = new Student();
    public Window1()
    {
        InitializeComponent();
        this.DataContext = stu;
    }
}

// ViewMode
class Student : INotifyPropertyChanged
{
    private double score;
    public event PropertyChangedEventHandler PropertyChanged;
    protected void InvokePropertyChanged(string property)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(property));
            }
        }

    /// <summary>
    /// 姓名
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 得分
    /// </summary>
    public double Score
    {
        get { return score; }
        set
        {
            if (score != value)
            {
                score = value;
                InvokePropertyChanged("Score");
            }
        }
    }
}

这是一个很简单的MVVM模型,相信熟悉WPF Binding的人都能看明白。下面是不同条件下的测试结果:

.NET框架UpdateSourceTrigger结果
.NET 4.0及以下版本Default能输入小数
.NET 4.0及以下版本PropertyChanged能输入小数
.NET 4.5及以上版本Default能输入小数
.NET 4.5及以上版本PropertyChanged不能输入小数

至此,这个现象已经描述清楚了,下面介绍原因和解决方法。

产生原因

据说转换器的问题,至于是微软有意为之还是bug就不得而知了。

解决方法

方法一:修改Xmal中的StringFormat,该方法的弊端就是每个绑定语句都要加StringFormat={}{0},如果StringFormat限定了格式,那么该方法不可用。

<Grid>
    <TextBox Text="{Binding Score,UpdateSourceTrigger=PropertyChanged,
        StringFormat={}{0}}"/>
</Grid>

方法二:可以在App.cs的入口函数中加入一行代码“FrameworkCompatibilityPreferences.KeepTextBoxDisplaySynchronizedWithTextProperty = false”

class App
{
    [STAThread]
    public static void Main(params string[] args)
    {
        FrameworkCompatibilityPreferences.KeepTextBoxDisplaySynchronizedWithTextProperty = false;
        Application app = new Application();
        app.Run(new Window1());
    }
}

// 或者
public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        FrameworkCompatibilityPreferences.KeepTextBoxDisplaySynchronizedWithTextProperty = false;
        base.OnStartup(e);
    }
}
标签: 暂无
最后更新:2020-09-27

王彦为

新生代农民工,十年医疗器械行业从业经验,现居苏州。爱生活,爱做梦。

打赏 点赞
< 上一篇
下一篇 >

文章评论

  • 西姆

    刚好遇到这个问题,尝试了你的方法,在双向绑定的时候仍然有问题,最终我还是把UpdateSourceTrigger改为Default了。
    谢谢分享好文,我已转载本文,如果有任何不妥可以联系我撤下。

    2020-03-17
    回复
  • 取消回复

    COPYRIGHT © 2022 王彦为. ALL RIGHTS RESERVED.

    苏ICP备16063331号-1