.net WinForms data binding using Lambda instead of property

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

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

Basically, I want to write a lambda expression instead of adding a property to my model. Is it possible?

+6
source share
2 answers

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

 var binding = new Binding("Visible", model, "Name"); binding.Format += (sender, args) => args.Value = (string)args.Value != "Default"; label.DataBindings.Add(binding); 
+4
source

Data binding Windows Forms recognizes the ICustomTypeDescriptor interface, which allows an object to decide at run time what properties it represents for data binding. Therefore, if you write an implementation of this, you can tell Windows Forms that you have all the properties that you have, and you can decide how to implement them.

Of course, this may not help - if you want to avoid adding a property, you can also avoid implementing a rather complex interface. The obvious solution would be to write a type whose task should act as a data source and bind to it, and not to the object in which you are currently bound.

Of course, if you do this, then it may just be easier for you to implement any property that you intend to implement on this shell.

In general, with data binding, you want to avoid binding directly to any basic model, precisely because you do not want to add things to your model solely in the interests of the user interface. This is why the “split presentation” is very popular - instead of directly connecting the model and viewing, you put something in the middle whose job is to mediate. Some call it the viewmodel, some call it the lead, but the basic principle is to share the view.

It seems that you are trying to achieve a separate presentation (which is good), but without introducing an additional type so that this middle layer goes somewhere. Why not just define a class (or set of classes) to work as this layer?

+2
source

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


All Articles