In WinForms, is it possible to databind without using properties?
I've got a class that has some properties that I can databind to, however it also has some user defined custom fields that are only available at runtime. e.g.:
public class Item
{
public int Id { get; set; } // I can databind controls to this
public string Name { get; set; } // I can databind controls to this
public object GetCustomFieldValue(string customFieldName);
public void SetCustomFieldValue(string customFieldName, object value);
}
Is there any way to hook into the binding logic to call the GetCustomFieldValue and SetCustomFieldValue methods instead of getting/setting properties?
I've tried creating a custom binding class that inherits from Binding with the hope of overriding some of the methods such as ReadValue() and WriteValue() but they're not virtual so that looks like a dead end.
Is there any other approach I could try?
Here's the solution I came up with in the end.
Create an interface for your custom fields:
Make sure your classes that have custom fields implement the interface:
Finally, I created an extension method to simplify adding the data bindings:
Then assuming you've got a form with a BindingSource and a TextBox control that you'll data bind to, you can use the above code like this in your form's Load event: