如何在Xamarin.Forms页面中从XAML传递Button作为CommandParameter?
我想在它自己的Command
传递一个Xamarin.Forms.Button
作为我的ViewModel的CommandParameter
。 我知道如何从背后的代码实现这一点,例如……
XAML (由于简洁而错过了大多数属性)
XAML.cs
public partial class MyTestPage { public MyTestPage() { InitializeComponent(); myButton.CommandParameter = myButton; } }
视图模型
public class MyViewModel : ViewModelBase { public MyViewModel() { ButtonClickCommand = new Command( (parameter) => { var view = parameter as Xamarin.Forms.Button; if (view != null) { // Do Stuff } }); } public ICommand ButtonClickCommand { get; private set; } }
…但是可以在XAML中声明CommandParameter
吗? 或者换句话说,将参数设置为按钮本身的绑定语法是什么?
顺便说一下,我已经尝试过CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
,但这不起作用。
谢谢,
Xamarin.Forms
有一个Reference标记扩展,它可以做到:
虽然,这是我第一次看到这种需求,你可能可以更好地将你的View与ViewModel分开,并通过使用更清晰的模式或不跨按钮共享命令来解决这个问题。
在您的ViewModel中
public YourViewModel() { ButtonClickCommand= new Command(ButtonClicked); } private async void ButtonClicked(object sender) { var view = sender as Xamarin.Forms.Button; }
应该工作,但我仍然不知道为什么你需要按钮? MVVM的重点是分离数据和UI。 你应该需要的所有东西都可以通过DataBindings完成。
如果上面的方法不起作用,唯一要尝试的是给按钮一个x:Key和CommandParamter = {StaticResource’x:Key’}