Favicon

Data binding to NumericUpDown

Peponi1/21/20252m

C#
SystemWindowsFormsNumericUpDownBinding

1. Introduction

Control의 data binding을 위해 다음 중 하나가 필요하다.

  • INotifyPropertyChanged 구현 : XAML 바인딩을 위해 사용하는 것과 동일하다.
  • 바인딩 대상 객체의 형식에 프로퍼티 변경 이벤트 구현

여기서는 INotifyPropertyChanged 인터페이스를 통한 바인딩 방법을 알아본다.

2. Example

using System.ComponentModel;
using System.Runtime.CompilerServices;
 
namespace NumericUpDownDataBinding
{
    public partial class Form1 : Form, INotifyPropertyChanged
    {
        // INotifyPropertyChanged 구현
        public event PropertyChangedEventHandler? PropertyChanged;
 
        private double _doubleData = 0;
 
        public double DoubleData
        {
            get => _doubleData;
            set
            {
                _doubleData = value;
                OnPropertyChanged();    // 프로퍼티가 변경되었음을 알림
            }
        }
 
        public Form1()
        {
            InitializeComponent();
 
            ConfigureComponents();
        }
 
        private void ConfigureComponents()
        {
            NumericUpDown numericUpDown = new();
            Button button = new();
            button.Click += delegate { DoubleData++; };     // 클릭할 때마다 +1
 
            numericUpDown.DataBindings.Add(new Binding(nameof(numericUpDown.Value), this, nameof(DoubleData)));
 
            TableLayoutPanel tableLayoutPanel = new()
            {
                ColumnCount = 2,
                Dock = DockStyle.Fill
            };
            tableLayoutPanel.Controls.Add(numericUpDown, 0, 0);
            tableLayoutPanel.Controls.Add(button, 1, 0);
 
            this.Controls.Add(tableLayoutPanel);
        }
 
        private void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

3. 참조 자료