c# - 如何在 Xamarin.Forms 页面中将按钮作为 CommandParameter 从 XAML 传递?

标签 c# xaml xamarin.forms commandparameter

我想将 Xamarin.Forms.Button 作为 CommandParameter 传递给我的 ViewModel。我知道如何从后面的代码中实现这一点,例如...

XAML (为简洁起见省略了大部分属性)

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

XAML.cs

public partial class MyTestPage
{
    public MyTestPage()
    {
        InitializeComponent();

        myButton.CommandParameter = myButton;
    }
}

View 模型

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

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

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

谢谢,

最佳答案

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

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

不过,这是我第一次看到这种需求,您可能可以更好地将 View 与 View 模型分开,并通过使用更清晰的模式或共享命令来解决此问题跨按钮。

关于c# - 如何在 Xamarin.Forms 页面中将按钮作为 CommandParameter 从 XAML 传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25912091/

相关文章:

c# - 使用 ItemAppearing 事件在 ListView 中向下滚动会跳过 Xamarin.Forms 中的记录

C# 和 IME - 获取当前输入文本

c# - Windows Mobile 应用程序中 DataGrid 的列宽

c# - 浏览图像时 App.config 中的连接字符串发生变化

c# - 使用 C# 在 GNU PLOT 中绘制图形

xaml - 如何在 XAML 中将 FontAttributes 设置为粗体和斜体?

c# - 使用拆分器使 ItemsControl 子项可调整大小

c# - 无法在 visual studio-15 中更改安装项目的平台

c# - Xamarin Forms 相对布局不会堆叠

xamarin - 如果未在使用模板的 XAML 中指定,我怎样才能使模板内的 HeightRequest 被忽略?