How to create a data binding for a control nested property?

Consider the following:

public interface IHaveProperties
{
    public MyProperties Properties { get; set; }
}

public class MyControlA : SomeWinFormsControl, IHaveProperties { ... }

public class MyControlB : SomeOtherWinFormsControl, IHaveProperties { ... }

public class MyProperties
{
    public int Foo { get; set; }
    public string Bar { get; set; }
    public double Baz { get; set; }
    ...
}

This allows us to add the same additional properties to many different controls, a base class that we cannot change, as well as save / load property sets.

Now that we have about a dozen different MyControlX, we realized that it would be nice to be able to bind data, say, to Properties.Bar.

Obviously, we could do this as follows:

public interface IHaveProperties
{
    public MyProperties Properties { get; set; }
    public string Bar { get; set; }
}

public class MyControlA : SomeWinFormsControl, IHaveProperties
{
    public string Bar
    {
        get { return Properties.Bar; }
        set { Properties.Bar = value; }
    }
}

... but we would have to put the same code in each of a dozen controls that seems smelly.

We tried this:

// Example: bind control property to nested datasource property
myTextBox.DataBindings.Add(new Binding("Text", myDataSet, "myDataTable.someColumn"))
// works!

// bind control (nested) Properties.Bar to datasource
myTextBox.DataBindings.Add(new Binding("Properties.Bar", someObject, "AProperty"))
// throws ArgumentException!

myControl.Properties.Bar MyProperties , ?

+4
1

:

TextBox.DataBindings.Add(new Binding("Text", someObject, "Properties.Bar"));
-2

Source: https://habr.com/ru/post/1544817/


All Articles