WPF Textbox does not allow decimal in net 4.5

2020-04-07


When we updagrade a WPF project from .NET 4.0 to .NET 4.5, We found some textboxes binding no longer work correctly.

Those textboxes used "UpdateSourceTrigger=PropertyChanged"

<TextBox x:Name="tb_name" Text="{Binding myValue1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, 
 TextChanged="value_TextChanged" />

1: Fix 1: Change UpdateSourceTrigger=PropertyChanged to UpdateSourceTrigger=LostFocus

But this fixing can not check the text 'on the fly' but only lost focus, which might not feed the function requirement.

2: Using StringFormat:

using StringFormat to fix this issue:

<TextBox x:Name="tb_name" Text="{Binding myValue1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, 
StringFormat={}{##.##}}" TextChanged="Hours_TextChanged" />

3:

Check Microsoft page about frameworkcompatibilitypreferences and keeptextboxdisplaysynchronizedwithtextproperty

        public MainWindow()
        {
            FrameworkCompatibilityPreferences.KeepTextBoxDisplaySynchronizedWithTextProperty = false;
            InitializeComponent();
        }

(not finished yet, check links below to finish this post)

4: Delay:

<TextBox x:Name="tb_name" Text="{Binding myValue1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Delay=300
 TextChanged="value_TextChanged" />


https://social.msdn.microsoft.com/Forums/azure/en-US/729de324-af72-44c5-825d-1248b5aec71b/behavior-of-text-property-for-textbox-control-is-different-in-net40-and-net452?forum=wpf

https://social.msdn.microsoft.com/Forums/vstudio/en-US/92ae5178-4a92-4784-b30b-226ecb1eb146/decimal-binding-issue-in-wpf?forum=wpf

https://docs.microsoft.com/en-us/dotnet/api/system.windows.frameworkcompatibilitypreferences.keeptextboxdisplaysynchronizedwithtextproperty?view=netframework-4.8rtial Views in ASP.NET Core](https://docs.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-3.1)