本文介绍了我如何通过从XAML的按钮CommandParameter在Xamarin.Forms页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在它自己的传递 Xamarin.Forms.Button 命令 CommandParameter 我的视图模型。我知道如何从背后例如代码实现这一目标...



XAML (大多数的属性错过了为简洁起见)



 <按钮X:NAME =myButton的
文字=我的按钮
命令={结合ButtonClickCommand}/> ;



XAML.cs



 公共部分类MyTestPage 
{
公共MyTestPage()
{
的InitializeComponent();

myButton.CommandParameter = myButton的;
}
}



视图模型

 公共类MyViewModel:ViewModelBase 
{
公共MyViewModel()
{
ButtonClickCommand =新命令(
(参数)=>
{
VAR视图=参数作为Xamarin.Forms.Button;!
如果(查看= NULL)
$ { b $ b //做的东西
}
});
}

公众的ICommand ButtonClickCommand {搞定;私人集; }
}



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

 <按钮X:?NAME = myButton的
文字=我的按钮
命令={结合ButtonClickCommand}
CommandParameter ={[WHAT会去这里]}/>



顺便说一句,我已经试过 CommandParameter ={绑定的RelativeSource = {的RelativeSource自}}并没有奏效。



谢谢,


解决方案

Xamarin.Forms 有一个参考标记扩展,做到了这一点:



<按钮X:NAME =myButton的
文字=我的按钮
命令={结合ButtonClickCommand}
CommandParameter ={X:参考myButton的}/>



虽然,这是我第一次看到这个需求,你可能可以更好地分离的从您的ViewModels的意见,并通过使用更清洁的方式解决这个问题,或者通过的的跨越按钮分享的命令。


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 (with most properties missed out for brevity)

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

XAML.cs

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

        myButton.CommandParameter = myButton;
    }
}

ViewModel

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

... 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]}"/>

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

Thanks,

解决方案

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.

这篇关于我如何通过从XAML的按钮CommandParameter在Xamarin.Forms页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 23:43