.net WinForms data binding using Lambda instead of property
Asked Answered
C

2

6

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?

Clouse answered 23/2, 2012 at 15:40 Comment(0)
L
4

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);
Lasalle answered 23/2, 2012 at 23:50 Comment(1)
Works perfectly. I was thinking about writing a small library to do this, but throwing this code into a method is all I need. Thanks!Carsick
M
2

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?

Mavismavra answered 23/2, 2012 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.