Jason Ge
Jason Ge

Reputation: 1

Windows Forms databinding to textbox with decimal value

I am trying to apply the MVVM pattern to traditional windows forms design. I have a textbox that hold a decimal value and I want to bind it to view model's Amount property. When I enter numbers in the textbox, the Amount property get's changed without issue. However, when I Remove all the input from the textbox, the Amount property setter is not called and therefore the amount is still the previous value.

I think because the empty string is not valid decimal value, the setter is not called. I have tried to define the amount as string and that worked. Is there any way to solve this issue without having to define Amount property as string?

My viewmodel code:

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WinFormsApp1
{
    internal partial class ViewModel : INotifyPropertyChanged
    {
        private decimal? _amount;

        public decimal? Amount
        {
            get => _amount;
            set
            {
                if (_amount == value)
                {
                    return;
                }

                _amount = value;

                // Notify the UI that the property has changed.
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        // Notify the UI that one of the properties has changed.
        private void OnPropertyChanged([CallerMemberName] string propertyName = "")
            => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

My Form.cs code:

namespace WinFormsApp1
{
    public partial class Form7 : Form
    {
        private ViewModel _viewModel;
        public Form7()
        {
            InitializeComponent();
            _viewModel = new ViewModel();
        }

        private void Form7_Load(object sender, EventArgs e)
        {
            BindingSource bindingSource = new BindingSource(_viewModel, null);
            txtAmount.DataBindings.Add(nameof(txtAmount.Text), bindingSource, nameof(_viewModel.Amount), true, DataSourceUpdateMode.OnPropertyChanged, null, "C2");
        }
    }
}

Upvotes: 0

Views: 80

Answers (0)

Related Questions