简体   繁体   English

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

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

In Xamarin forms, we set a binding on a control like:在 Xamarin 表单中,我们在控件上设置绑定,例如:

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

Is there a way to store the second parameter (the lambda expression) in a variable?有没有办法将第二个参数(lambda 表达式)存储在变量中?

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>>'无法从“System.Func<someViewModel, someType>”转换为“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> .在这种情况下,通用source参数的类型为Expression<Func<MyViewModel, string>> ,而不是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?请参阅为什么要使用 Expression> 而不是 Func? for more details.了解更多详情。

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

Yes.是的。 You can do it with delegates.你可以用代表来做。 You can refer this tutorial by MSDN to learn how to do that.您可以通过 MSDN参考本教程以了解如何执行此操作。 If the name of Viewmodel class you use for page is MyViewModel , you can do something like this.如果用于页面的 Viewmodel 类的名称是MyViewModel ,则可以执行以下操作。

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

Then pass myDelegate to the binding statement as second parameter.然后将myDelegate作为第二个参数传递给绑定语句。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM