A place for spare thoughts

17/04/2012

Binding to WPF TextBox seems to be broken in .NET 4.5 Beta

Filed under: wpf — Ivan Danilov @ 15:18

Recently I found that update from .NET 4.0 to .NET 4.5 Beta brings one nasty bug with it to the WPF. As Scott mentioned, .NET 4.5 is in-place upgrade to .NET 4.0, thus now I experience the same problem in any app targeted at .NET 4.0 as well.

OK, let’s go closer to the actual problem.

Create new WPF application, in MainWindow.xaml put the following:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
  <Grid>
    <TextBox Text="{Binding Path=Prop, UpdateSourceTrigger=PropertyChanged}" />
  </Grid>
</Window>

And here is MainWindow.xaml.cs:

using System.Windows.Controls;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public decimal Prop { get; set; }
    }
}

That’s all. Now, run the application. You will have TextBox stretched to the entire window with ‘0’ inside. Try to enter decimal dot (or whatever you have on your current culture for separating integer part from fractional). Nothing happens.

Now go to project properties and switch target framework to .NET 3.5 (you have to delete some references that do not exist in that framework, but I didn’t use them here anyway, so it is OK). Run the app – everything will work fine, you can enter decimal dot.

I suppose the problem is somewhere in property changing/coercion mechanism: WPF tries to parse value ‘0.’ as decimal, it succeeds and TextBox’s contents changed back to ‘0’ which is decimal value converted to string. It is also indirectly proven by the fact that if you have ‘0’ and press ‘1’ – you will have ‘1’ instead of ’01’ which one could expect. Similarly, you can’t put ‘+’ sign before number, but can put ‘-‘ sign before non-zero number. And you can’t put any sign before zero. And even more vivid proof – if you have any invalid value (i.e. that can’t be parsed as decimal) – you can do any edits you like and they are handled correctly.

Here is feedback at MS connect site about the problem.

UPD: At connect MS replied that 4.0 behavior was actually a bug and they fixed it in 4.5. In fact the fix is worse from usability point than bug was as it seems to me… see the discussion at MS Connect site (link above) for details.

Blog at WordPress.com.