如何在 Xamarin.Forms 页面中将 Button 作为 CommandParameter 从 XAML 传递? [英] How do I pass the Button as CommandParameter from XAML in a Xamarin.Forms Page?

查看:51
本文介绍了如何在 Xamarin.Forms 页面中将 Button 作为 CommandParameter 从 XAML 传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 Xamarin.Forms.Button 在它自己的 Command 中作为 CommandParameter 传递给我的 ViewModel.我知道如何从背后的代码中实现这一点,例如...

I would like to pass a Xamarin.Forms.Button in it's own Command as the CommandParameter to my ViewModel. I know how to achieve this from the code behind e.g. ...

XAML (为简洁起见省略了大多数属性)

<Button x:Name="myButton"
    Text="My Button"
    Command="{Binding ButtonClickCommand}"/>

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 吗?或者换句话说,将参数设置为按钮本身的绑定语法是什么?

... BUT is it possible to declare the CommandParameter in the XAML itself? Or in other words what is the binding syntax to set the parameter to the button itself?

<Button x:Name="myButton"
        Text="My Button"
        Command="{Binding ButtonClickCommand}"
        CommandParameter="{[WHAT WOULD GO HERE]}"/>

顺便说一句,我已经尝试过 CommandParameter="{Binding RelativeSource={RelativeSource Self}}" 但没有奏效.

btw I've already tried CommandParameter="{Binding RelativeSource={RelativeSource Self}}" and that didn't work.

谢谢,

推荐答案

Xamarin.Forms 有一个 Reference 标记扩展可以做到这一点:

Xamarin.Forms has a Reference markup extension that does just that:

<Button x:Name="myButton"
    Text="My Button"
    Command="{Binding ButtonClickCommand}"
    CommandParameter="{x:Reference myButton}"/>

虽然,这是我第一次看到这种需求,您可能可以更好地将视图与视图模型分开,并通过使用更简洁的模式或共享命令来解决此问题跨按钮.

Although, this is the first time I'm seeing this need, and you probably can better separate your Views from your ViewModels and solve this by using a cleaner pattern, or by not sharing a command across buttons.

这篇关于如何在 Xamarin.Forms 页面中将 Button 作为 CommandParameter 从 XAML 传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆