Xamarin.Forms - 可以对 SetBinding() lambda 参数进行变量化吗?

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

在 Xamarin 表单中,我们在控件上设置绑定,例如:

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

有没有办法将第二个参数(lambda 表达式)存储在变量中?

基于this answer,我试过:

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

但是第二个参数有一个红色的下划线和错误

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

是的。在这种情况下,通用 source 参数的类型为 Expression<Func<MyViewModel, string>>,而不是 Func<MyViewModel, string>。这两种类型都以相同的方式初始化,但含义却截然不同。参见 为什么要使用 Expression> 而不是 Func? 了解更多详情。

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

是的。你可以和代表一起做。您可以参考此 tutorial by MSDN 了解如何操作。如果您用于页面的 Viewmodel class 的名称是 MyViewModel,您可以这样做。

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

然后将myDelegate作为第二个参数传递给绑定语句。

myLabel.SetBinding<MyViewModel>(Label.TextProperty, myDelegate);