Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't insert a decimal into a TextBox?

Here’s my ViewModel:

public class ViewModelData : INotifyPropertyChanged
{
    private decimal? myValue;
    public decimal? MyValue
    {
        get { return myValue; }
        set
        {
            myValue = value;
            OnPropertyChanged(nameof(MyValue));
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

And here’s my TextBox:

<TextBox 
    Name="MyValueBox" 
    Text="{Binding MyValue, UpdateSourceTrigger=PropertyChanged}" 
    HorizontalAlignment="Center" 
    VerticalAlignment="Top" 
    Width="112" 
    Margin="0,96,0,0"/>

But, when I try to insert the value 1.0 for example, I can type 1, but later can’t type ..
Instead, I can write text1.0, or 10 and than move cursor after 1 and type . (between 1 and 0).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why? And how can I fix this?

>Solution :

Setting UpdateSourceTrigger=PropertyChanged on the binding means that your source property will be set on each key press. And you cannot set a decimal? to the value "1." in C#.

So you can either remove UpdateSourceTrigger=PropertyChanged to use the default behavior of setting the source property once the focus leaves the TextBox.

Or you can try to handle the PreviewTextInput event as suggested here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading