18

我想将Xamarin.Forms.Button它自己的Command一个传递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;
    }
}

视图模型

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; }
}

...但是可以CommandParameter在 XAML 本身中声明吗?或者换句话说,将参数设置为按钮本身的绑定语法是什么?

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

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

谢谢,

4

4 回答 4

25

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.

于 2014-09-18T14:05:27.603 回答
4
 <Button x:Name="myButton"
        Text="My Button"
        Command="{Binding ButtonClickCommand}"
        CommandParameter="{x:Reference myButton}"/>

在您的视图模型中

public YourViewModel()
{
    ButtonClickCommand= new Command(ButtonClicked);
}

private async void ButtonClicked(object sender)
{
    var view = sender as Xamarin.Forms.Button;
}
于 2018-05-10T18:28:44.983 回答
0
<Button x:Name="myButton"
    Text="My Button"
    Command="{Binding ButtonClickCommand}"
    CommandParameter={Binding RelativeSource=
                               {RelativeSource
                                Mode=FindAncestor,
                                AncestorType={x:Type Button}}/>

应该可以工作,但我仍然不知道为什么需要按钮?MVVM 的重点是将数据和 UI 分开。您需要对按钮执行的所有操作都可以通过 DataBindings 完成。

如果上述方法不起作用,那么唯一要尝试的方法是给按钮一个 x:Key 和 CommandParamter = {StaticResource 'x:Key'}

于 2014-09-18T12:27:57.950 回答
0

一个简单的方法是:

在 XAML 中:

 <Button Text="BUTTON-TEST"
            Clicked="Avaliar"
            CommandParameter="like"/>

在 C# 中:

private void Avaliar(object sender, EventArgs e)
{
     Console.WriteLine(((Button)sender).CommandParameter);
}
于 2020-04-22T12:32:20.790 回答