3
votes

I'm trying to bind my ListView Item to Command from my parent ViewModel. The problem is that I would like to add CommandParameter with current Item

Basically, in WPF i would do something like

<MyItem Command="{Binding ElementName=parent", Path=DataContext.MyCommand}" CommandParameter="{Binding}"/>

In Xamarin Forms ElementName is not working, so the way is to use BindingContext, but how I should use it (if one of my binding points to parent, second one to self)?

I have tried

<MyItem Command="{Binding BindingContext.RemoveCommand, Source={x:Reference parent}}" CommandParameter="{Binding }" />

But it does not work (seems it not changing Source).

I know, that with normal binding a way is to use BindingContext="{x:Reference parent}", but it won't work in this example, because I need Self binding for CommandParameter

How can i do it?

1
Additionally, MyItem is a child of DataTemplate - Tomasz
It's not clear to me what are you trying to do. Can you give some context to your question? What are you trying to achieve in the UI? - Sten Petrov
Not sure if I can follow...wouldn't you simply have a Parent property on your binding context and call RemoveCommand on that? Like: Command="{Binding Parent.RemoveCommand}"? You don't want to call the command on the UI element (that's what x:Reference is for). The sender of the command will be the current element, so no need to use a parameter here. - Krumelur

1 Answers

1
votes

I understand you want to execute a command on the parent node of your current node but pass the current node as a parameter. If that is the case, you can solve it like this:

Here's the model we bind to. It has a Parent property and it defines an ICommand (please note that all is C#6 code, so you'll need XS or VS2015!):

public class BindingClass
{
    public BindingClass (string title)
    {
        this.TestCommand = new TestCommandImpl (this);
        this.Title = title;
    }

    public string Title { get; }
    public ICommand TestCommand { get; }
    public BindingClass Parent { get; set; }
}

In the code behind, the binding context is set:

this.BindingContext = new BindingClass ("Bound Button") {
    Parent = new BindingClass ("Parent")
};

And in the XAML, we have a button that calls the command of the parent node and passes the current node as a parameter:

<Button
    x:Name="btnTest"
    Text="{Binding Title}"
    Command="{Binding Parent.TestCommand}"
    CommandParameter="{Binding}"
    VerticalOptions="CenterAndExpand"
    HorizontalOptions="CenterAndExpand"/>