Favicon

Data binding to TextBox

Peponi1/21/20252m

C#
SystemWindowsFormsTextBoxBinding

1. Introduction

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

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

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

2. Example

using System.ComponentModel;
using System.Runtime.CompilerServices;
 
namespace TextBoxDataBinding
{
    public partial class Form1 : Form, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;
 
        private string _textData = string.Empty;
 
        public string TextData
        {
            get => _textData;
            set
            {
                _textData = value;
                OnPropertyChanged();    // 프로퍼티가 변경되었음을 알림
            }
        }
 
        public Form1()
        {
            InitializeComponent();
 
            ConfigureComponents();
        }
 
        private void ConfigureComponents()
        {
            TextBox textbox1 = new();   // string 그대로 출력
            TextBox textbox2 = new();   // Format 적용된 string 출력
            Button button = new();
            button.Click += delegate { TextData += "a"; };      // TextData 변경
 
            textbox1.DataBindings.Add(new Binding(nameof(textbox1.Text), this, nameof(TextData), false, DataSourceUpdateMode.OnPropertyChanged));
            var binding = new Binding(nameof(textbox2.Text), this, nameof(TextData), false, DataSourceUpdateMode.OnPropertyChanged);
            binding.Format += TextBoxFormat;
            binding.Parse += TextBoxParse;
            textbox2.DataBindings.Add(binding);
 
            TableLayoutPanel tableLayoutPanel = new()
            {
                ColumnCount = 3,
                Dock = DockStyle.Fill
            };
            tableLayoutPanel.Controls.Add(textbox1, 0, 0);
            tableLayoutPanel.Controls.Add(textbox2, 1, 0);
            tableLayoutPanel.Controls.Add(button, 2, 0);
 
            this.Controls.Add(tableLayoutPanel);
        }
 
        private void TextBoxFormat(object? sender, ConvertEventArgs e)
        {
            // 입력 값에 대한 formatting이 필요한 경우
            if (e.DesiredType == typeof(string))
            {
                e.Value = $"Format - {e.Value}";
            }
        }
 
        private void TextBoxParse(object? sender, ConvertEventArgs e)
        {
            // 반환 값에 대한 formatting이 필요한 경우
            if (e.DesiredType == typeof(string) && e.Value is not null)
            {
                if (((string)e.Value).Contains("Format - "))
                {
                    e.Value = ((string)e.Value).Replace("Format - ", "");
                }
                else e.Value = "";
            }
        }
 
        private void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

3. 참조 자료