3

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>>'

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
jbyrd
  • 5,287
  • 7
  • 52
  • 86
  • take a look at this: https://developer.xamarin.com/api/member/Xamarin.Forms.BindableObjectExtensions.SetBinding%7BTSource%7D/p/Xamarin.Forms.BindableObject/Xamarin.Forms.BindableProperty/System.Linq.Expressions.Expression%7BSystem.Func%7BTSource,System.Object%7D%7D/Xamarin.Forms.BindingMode/Xamarin.Forms.IValueConverter/System.String/ – Gusman May 03 '16 at 16:25

2 Answers2

2

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);
Community
  • 1
  • 1
Giorgi
  • 30,270
  • 13
  • 89
  • 125
  • Ah, an Expression, ok awesome...now apparently, for the return value of the lambda expression, it is expecting an object - `Argument 3: cannot convert from 'Systemlinq.Expressions.Expression>' to 'Systemlinq.Expressions.Expression>'`...? – jbyrd May 05 '16 at 00:49
  • Oh, I just had to change the `string` param to a generic `object`, so the following worked: `Expression> myExpression = viewModel => viewModel.LabelText;` – jbyrd May 12 '16 at 13:48
0

Yes. You can do it with delegates. You can refer this tutorial by MSDN to learn how to do that. If the name of Viewmodel class you use for page is MyViewModel, you can do something like this.

delegate string del(MyViewModel viewModel);
 del myDelegate = x => x * x.LabelString;

Then pass myDelegate to the binding statement as second parameter.

myLabel.SetBinding<MyViewModel>(Label.TextProperty, myDelegate);
Sreeraj
  • 2,306
  • 2
  • 18
  • 31