Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin.Forms - Possible to variable-ize a SetBinding() lambda parameter?

In Xamarin forms, we set a binding on a control like:

myLabel.SetBinding<MyViewModel>(Label.TextProperty, viewModel => viewModel.LabelText);

Is there a way to store the second parameter (the lambda expression) in a variable?

Based on this answer, I've tried:

Func<MyViewModel, string> myLambda = viewModel => viewModel.LabelText;
myLabel.SetBinding<MyViewModel>(Label.TextProperty, myLambda);

But the 2nd parameter gets a red underline with the error

cannot convert from 'System.Func<someViewModel, someType>' to 'System.Linq.Expressions<System.Func<someViewModel, object>>'

like image 313
jbyrd Avatar asked Jan 17 '26 19:01

jbyrd


1 Answers

Yes it is. The generic source parameter in this case is of type Expression<Func<MyViewModel, string>>, not Func<MyViewModel, string>. Both of these types are initializer in the same way but have very different meaning. See Why would you use Expression> rather than Func? for more details.

Expression<Func<MyViewModel, string>> myLambda;
myLambda = viewModel => viewModel.LabelText;
myLabel.SetBinding<MyViewModel>(Label.TextProperty, myLambda);
like image 111
Giorgi Avatar answered Jan 20 '26 08:01

Giorgi