Data binding to PropertyGrid
Peponi │ 1/21/2025 │ 2m
C#
SystemWindowsFormsPropertyGridBinding
Data binding to PropertyGrid
1/21/2025
2m
Peponi
C#
SystemWindowsFormsPropertyGridBinding
1. Introduction
Control
의 data binding을 위해 다음 중 하나가 필요하다.
- INotifyPropertyChanged 구현 : XAML 바인딩을 위해 사용하는 것과 동일하다.
- 바인딩 대상 객체의 형식에 프로퍼티 변경 이벤트 구현
여기서는 INotifyPropertyChanged
인터페이스를 통한 바인딩 방법을 알아본다.
2. Example
public class Account(int id, string name) : INotifyPropertyChanged
{
// INotifyPropertyChanged 구현
public event PropertyChangedEventHandler? PropertyChanged;
private int _id = id;
public int ID
{
get => _id;
set
{
_id = value;
OnPropertyChanged(); // 프로퍼티가 변경되었음을 알림
}
}
private string _name = name;
public string Name
{
get => _name;
set
{
_name = value;
OnPropertyChanged(); // 프로퍼티가 변경되었음을 알림
}
}
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace PropertyGridDataBinding
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ConfigureComponents();
}
private void ConfigureComponents()
{
BindingList<Account> accounts =
[
new(0,"A"),
new(1,"B"),
new(2,"C")
];
BindingSource source = new(accounts, null);
ListBox listBox = new() { Width = 200, DataSource = source }; // PropertyGrid에 선택된 item 표시
PropertyGrid grid = new() { Width = 200, Height = 300 };
Button button = new();
button.Click += Update; // ID, Name 변경
grid.DataBindings.Add(new Binding(nameof(grid.SelectedObject), source, null));
TableLayoutPanel tableLayoutPanel = new()
{
ColumnCount = 3,
Dock = DockStyle.Fill
};
tableLayoutPanel.Controls.Add(listBox, 0, 0);
tableLayoutPanel.Controls.Add(grid, 1, 0);
tableLayoutPanel.Controls.Add(button, 2, 0);
this.Controls.Add(tableLayoutPanel);
void Update(object? sender, EventArgs e)
{
if (grid.SelectedObject is not null && grid.SelectedObject is Account item)
{
item.ID++;
item.Name += "a";
}
}
}
}
}