Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind textbox to float value. Unable to input dot / comma

Tags:

c#

.net

wpf

When I try to input a DOT or a COMMA in a textbox, for example 1.02 or 83,33 the textbox prevents me to input such a value (and the input turns red). The textbox is bound to a float property. Why?

I have bound a textbox to a float Property Power of a class implementing INotifyPropertyChanged.

private float _power;

public float Power
{
    get { return _power; }
    set
    {
        _power = value;
        OnPropertyChanged("Power");
    }
}

In Xaml

<TextBox Name="txtPower" Height="23" TextWrapping="Wrap" Text="{Binding Path=Power, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>

I have no custom validation at all right now.

Also tried decimal but it does not work either. For string everything works fine.

like image 815
LukeSolar Avatar asked Jan 30 '13 09:01

LukeSolar


3 Answers

If you have .NET 4.5 or newer, you may enforce the pre 4.5 behaviour

System.Windows.FrameworkCompatibilityPreferences.KeepTextBoxDisplaySynchronizedWithTextProperty = false;

See Sebastian Lux's blog: With .NET 4.5 it is no longer possible to enter a separator character (comma or dot) with UpdateSourceTrigger = PropertyChanged by default. Microsoft says, this intended.

like image 121
xmedeko Avatar answered Nov 02 '22 16:11

xmedeko


Try adding a StringFormat definition to the binding. Like so:

<TextBox Name="txtPower" Height="23" 
    TextWrapping="Wrap" Text="{Binding Path=Power, Mode=TwoWay, 
    UpdateSourceTrigger=PropertyChanged,StringFormat=N2}"></TextBox>
like image 27
yonigozman Avatar answered Nov 02 '22 18:11

yonigozman


to fix dot and comma issue in textbox binding to decimal or float

1-  UpdateSourceTrigger = LostFocus 
2-  add string format StringFormat={}{0:#.##} to escape unneeded zeros 


<TextBox Name="txtPower" Height="23" 
         TextWrapping="Wrap" Text="{Binding Path=Power, Mode=TwoWay, 
         UpdateSourceTrigger=LostFocus ,StringFormat={}{0:#.##}}"></TextBox>
like image 1
Hisham Avatar answered Nov 02 '22 17:11

Hisham