2
votes

Using Prism for Xamarin Forms, I have a ListView like this:

<ListView ItemsSource="{Binding Conditions}">
    <ListView.ItemTemplate>
          <DataTemplate>
               <ViewCell>
                   <Grid Margin="4" RowSpacing="0">
                        <Button Command="{Binding DoSomething}"/>
                    </Grid>
               </ViewCell>
           </DataTemplate>
     </ListView.ItemTemplate>
</ListView>

where Conditions is an ObservableCollection of ConditionViewModel and the DoSomething command is located in the ViewModel of the Page.

So, of course, the binding won't work here because it's bindingcontext is going to be an individual ConditionViewModel item.

I know that Relative bindings are not available in Xamarin and the prescribed solution appears to be to directly apply {x:Reference SomeViewModel}. But using Prism, the View doesn't have direct access to its ViewModel, so this is not possible.

I've also looked at this, in an attempt to get a RelativeContext markup extension: https://github.com/corradocavalli/Xamarin.Forms.Behaviors/blob/master/Xamarin.Behaviors/Extensions/RelativeContextExtension.cs but, get an exception that the RootObject is null.

Any other solution?

1

1 Answers

5
votes

If I understand your question correctly, what you want is something like this:

ViewModel:

public class MyPageViewModel : BindableBase
{
    public MyPageViewModel()
    {
        MyCommand = new DelegateCommand<MyModel>( ExecuteMyCommand );
    }

    public ObservableCollection<MyModel> Collection { get; set; }

    public DelegateCommand<MyModel> MyCommand { get; }

    private void ExecuteMyCommand( MyModel model )
    {
        // Do Foo
    }
}

View;

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyProject.Views.MyPage"
             x:Name="page">
    <ListView ItemsSource="{Binding Collection}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Button Command="{Binding BindingContext.MyCommand,Source={x:Reference page}}"
                            CommandParameter="{Binding .}" />
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>