Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User can't type '.' in the textbox that have been bound to a float value while UpdateSourceTrigger is PropertyChanged in WPF

I have a funny problem with Float data type and UpdateSourceTrigger in WPF.I have a property with float data type and bind it to a TextBox and set UpdateSourceTrigger of the Binding to PropertyChanged,but WPF dosen't let me type '.' in the TextBox unless i change UpdateSourceTrigger to LostFocus.I think it's because of we can not type '.' in the end of float value.I don't have any idea how can i fix it because i need to type '.' and set UpdateSourceTrigger to PropertyChanged.

The property is:

  public float? Amount
    {
        get;set;
    }

And in the XAML:

    <TextBox
        Text="{Binding Amount , UpdateSourceTrigger=PropertyChanged}"/>
like image 418
mahboub_mo Avatar asked Jun 17 '13 07:06

mahboub_mo


1 Answers

Maybe it would help if you add a StringFormat statement in your binding:

<TextBox
    Text="{Binding Amount, StringFormat='{}{##.##}', UpdateSourceTrigger=PropertyChanged}"/>    

Update: I saw that my first answer throws some binding errors..

An other option is working with a converter (works, but a bit dirty ;-) ):

...
<Window.Resources>        
    <local:FloatConverter x:Key="FloatConverter" />
</Window.Resources>
...
<TextBox Text="{Binding Amount, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource FloatConverter}}"></TextBox>

Converter:

public class FloatConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
     return value;
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
     // return an invalid value in case of the value ends with a point
     return value.ToString().EndsWith(".") ? "." : value;
  }

}

like image 140
rhe1980 Avatar answered Oct 21 '22 04:10

rhe1980