Search code examples
c#wpftextboxdecimal

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).

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.