Data binding to MaskedTextBox
Peponi │ 1/21/2025 │ 2m
C#
SystemWindowsFormsMaskedTextBoxBinding
Data binding to MaskedTextBox
1/21/2025
2m
Peponi
C#
SystemWindowsFormsMaskedTextBoxBinding
1. Introduction
Control
의 data binding을 위해 다음 중 하나가 필요하다.
- INotifyPropertyChanged 구현 : XAML 바인딩을 위해 사용하는 것과 동일하다.
- 바인딩 대상 객체의 형식에 프로퍼티 변경 이벤트 구현
여기서는 INotifyPropertyChanged
인터페이스를 통한 바인딩 방법을 알아본다.
2. Example
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace MaskedTextBoxDataBinding
{
public partial class Form1 : Form, INotifyPropertyChanged
{
// INotifyPropertyChanged 구현
public event PropertyChangedEventHandler? PropertyChanged;
private string _inputText = string.Empty;
public string InputText
{
get => _inputText;
set
{
_inputText = value;
OnPropertyChanged(); // 프로퍼티가 변경되었음을 알림
}
}
public Form1()
{
InitializeComponent();
ConfigureComponents();
}
private void ConfigureComponents()
{
MaskedTextBox textBox = new() { Mask = "000-0000-0000" };
Button button = new();
button.Click += delegate { InputText = "010-1234-5678"; }; // 문자열 초기화
textBox.DataBindings.Add(new Binding(nameof(textBox.Text), this, nameof(InputText)));
TableLayoutPanel tableLayoutPanel = new()
{
ColumnCount = 2,
Dock = DockStyle.Fill
};
tableLayoutPanel.Controls.Add(textBox, 0, 0);
tableLayoutPanel.Controls.Add(button, 1, 0);
this.Controls.Add(tableLayoutPanel);
}
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}