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>>'
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With