Favicon

Data binding to CheckBox

Peponi1/21/20252m

C#
SystemWindowsFormsCheckBoxBinding

1. Introduction

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

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

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

2. Example

using System.ComponentModel;
using System.Runtime.CompilerServices;
 
namespace CheckBoxDataBinding
{
    public partial class Form1 : Form, INotifyPropertyChanged
    {
        // INotifyPropertyChanged 구현
        public event PropertyChangedEventHandler? PropertyChanged;
 
        private bool _boolData = false;
 
        public bool BoolData
        {
            get => _boolData;
            set
            {
                _boolData = value;
                OnPropertyChanged();    // 프로퍼티가 변경되었음을 알림
            }
        }
 
        public Form1()
        {
            InitializeComponent();
 
            ConfigureComponents();
        }
 
        private void ConfigureComponents()
        {
            CheckBox checkBox1 = new();
            Button button = new();
            button.Click += delegate { BoolData = !BoolData; };     // 클릭할 때마다 뒤집기
 
            checkBox1.DataBindings.Add(new Binding(nameof(checkBox1.Checked), this, nameof(BoolData)));
 
            TableLayoutPanel tableLayoutPanel = new()
            {
                ColumnCount = 2,
                Size = this.Size,
                Dock = DockStyle.Fill
            };
            tableLayoutPanel.Controls.Add(checkBox1, 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. 참조 자료