在Datatemplate(XF / Prism)中绑定命令

时间:2016-12-13 19:05:09

标签: c# xamarin xamarin.forms prism

使用Prism for Xamarin Forms,我有一个像这样的ListView:

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

其中Conditions是ConditionViewModel的ObservableCollection,而DoSomething命令位于Page的ViewModel中的

因此,当然,绑定在这里不起作用,因为它的bindingcontext将是一个单独的ConditionViewModel项。

我知道Xamarin中没有相对绑定,并且规定的解决方案似乎是直接应用{x:Reference SomeViewModel}。但是使用Prism,View无法直接访问其ViewModel,因此这是不可能的。

我也看过这个,试图获得RelativeContext标记扩展: https://github.com/corradocavalli/Xamarin.Forms.Behaviors/blob/master/Xamarin.Behaviors/Extensions/RelativeContextExtension.cs 但是,获取RootObject为空的异常。

还有其他解决方案吗?

1 个答案:

答案 0 :(得分:4)

如果我理解你的问题,你想要的是这样的:

视图模型:

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

查看;

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