Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net WinForms data binding using Lambda instead of property

In my project I have a model and I want to bind the visible state of a label using one of the model properties. I do not want to add another ShowLabel property to the model. I want to be able to write something like this:

label.Bindings.Add("Visible", model, m => m.Name != "Default");

Basically I want to be able to write a lambda expression instead of adding a property to my model. Is this possible?

like image 662
Radu D Avatar asked Feb 23 '12 15:02

Radu D


2 Answers

Yes, you can do this using the Format event of the Binding class. You'll still bind to the property in question, but your Format event handler will return a different value (a bool in this case).

var binding = new Binding("Visible", model, "Name");
binding.Format += (sender, args) => args.Value = (string)args.Value != "Default";
label.DataBindings.Add(binding);
like image 115
Igby Largeman Avatar answered Oct 06 '22 00:10

Igby Largeman


Windows Forms data binding recognizes the ICustomTypeDescriptor interface, which allows an object to decide at runtime which properties it presents to data binding. So if you write an implementation of that, you can tell Windows Forms that you have whatever properties you feel like having, and you can decide how to implement them.

Of course, that may not help - if you wanted to avoid adding a property, you may also want to avoid implementing a fairly complex interface. The obvious solution would be to write a type whose job is to act as the data source and bind to that instead of whichever object you're currently binding to.

Of course, if you do that it's probably then easier just to implement whatever property you were going to implement on that wrapper instead.

In general with databinding, you want to avoid binding directly to some underlying model, precisely because you don't want to have to add things to your model purely for the benefit of the UI. This is why 'separated presentation' is very popular - instead of connecting the model and view directly, you stick something in the middle whose job is to mediate. Some call this a viewmodel, some call it a presenter, but the basic principle is always separation of presentation.

It sounds like you're trying to achieve separate of presentation (which is good) but without introducing an extra type so that this middle layer has somewhere to go. Why not just define a class (or a set of classes) to act as that layer?

like image 34
Ian Griffiths Avatar answered Oct 05 '22 23:10

Ian Griffiths