How do I pass the Button as CommandParameter from XAML in a Xamarin.Forms Page?

◇◆丶佛笑我妖孽 提交于 2019-11-30 17:36:21

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.

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

In your ViewModel

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

private async void ButtonClicked(object sender)
{
    var view = sender as Xamarin.Forms.Button;
}
<Button x:Name="myButton"
    Text="My Button"
    Command="{Binding ButtonClickCommand}"
    CommandParameter={Binding RelativeSource=
                               {RelativeSource
                                Mode=FindAncestor,
                                AncestorType={x:Type Button}}/>

Should work, but im still at a loss why you need the button? The point of MVVM is to seperate Data and UI. everything you should need todo to the button can be done via DataBindings.

If the above doesnt work, the only other thing to try is to give the button an x:Key and CommandParamter = {StaticResource 'x:Key'}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!