Всё проще, чем кажется. Достаточно реализовать в своём объекте интерфейс IBindableComponent - и можно привязать его свойства (поля) к любому data source:
| Код | using System; using System.Data; using System.Windows.Forms;
class Program { static void Main(string[] args) { // создаём таблицу DataTable table = new DataTable(); table.Columns.Add("Id", typeof(int)); table.Columns.Add("Text", typeof(string)); table.PrimaryKey = new DataColumn[] { table.Columns[0] }; table.Rows.Add(1, string.Empty);
// создаём объект TestObject obj = new TestObject();
// привязка свойства "TheText" к полю таблицы obj.DataBindings.Add("TheText", table, "Text");
// проверяем работу привязки table.Rows[0]["Text"] = "1234"; Console.WriteLine("Row.Text = " + table.Rows[0]["Text"]); Console.WriteLine("obj.TheText = " + obj.TheText);
// и наоборот obj.TheText = "5678"; obj.BindingContext[table].EndCurrentEdit(); Console.WriteLine("Row.Text = " + table.Rows[0]["Text"]); Console.WriteLine("obj.TheText = " + obj.TheText); } }
/// <summary> /// Тестовый класс, реализующий поддержку Data Bindings /// </summary> class TestObject : IBindableComponent { private string theText = string.Empty; /// <summary> /// Свойство, которое можно будет биндить на data source /// </summary> public string TheText { get { return theText; } set { theText = value; } }
/// <summary> /// Конструктор. Создаём BindingContext и коллекцию DataBindings /// </summary> public TestObject() { _context = new BindingContext(); _bindings = new ControlBindingsCollection(this); }
// ниже - простейшая реализация интерфейса IBindableComponent
BindingContext _context; ControlBindingsCollection _bindings; public event EventHandler Disposed;
public BindingContext BindingContext { get { return _context; } set { _context = value; } }
public ControlBindingsCollection DataBindings { get { return _bindings; } }
public System.ComponentModel.ISite Site { get { return null; } set { } }
public void Dispose() { } }
|
|