将参数从列表传递给ViewModel构造函数

时间:2020-09-15 10:39:43

标签: xaml xamarin mvvm xamarin.forms viewmodel

我有一个玩家列表

public ObservableCollection<PlayerModel> Players { get; set; }

flexlayout可绑定项设置为玩家列表

<FlexLayout x:Name="playerscollection" Wrap="Wrap" BindableLayout.ItemsSource="{Binding Players}"/>

items视图是带有ViewModel“ PlayerVieModel”的单独的内容视图“ PlayerView”,具有参数化的构造函数

PlayerView =>

<ContentView.Content>

        <StackLayout>


        <StackLayout  Orientation="Horizontal" HorizontalOptions="FillAndExpand" >

            <Entry x:Name="entry" Placeholder="الاسم" HorizontalOptions="FillAndExpand"  Text="{Binding PlayerName}" />
            <Label  TextColor="Black" FontSize="Medium" HorizontalOptions="End" Text="اللاعب" VerticalOptions="Center"/>
        </StackLayout>

        <views:SportsListView x:Name="sportsList" BindingContext="{Binding ListViewModel}"   
                                              HorizontalOptions="FillAndExpand"
                                              Pickervisibility="True"/>

        <Label x:Name="payment" Text="{Binding Source={x:Reference sportsList}, Path=BindingContext.SportsTotalPayments, StringFormat='{0:D2}'}" HorizontalTextAlignment="Start" Margin="0,0,10,0" Padding="0" VerticalTextAlignment="Center" HorizontalOptions="CenterAndExpand" FontSize="20"/>


    </StackLayout>

</ContentView.Content>

public PlayerViewModel(bool showPicker = true, PlayerModel player = null){}

我需要将列表视图项绑定到PlayerVieModel

<FlexLayout x:Name="playerscollection" Wrap="Wrap" BindableLayout.ItemsSource="{Binding Players}">
    <BindableLayout.ItemTemplate>
        <DataTemplate>
            <views:PlayerView >
                <views:PlayerView.BindingContext>
                    <viewModels:PlayerViewModel>
                        <x:Arguments>
                                <x:Boolean>false</x:Boolean>
                                <models:PlayerModel/>
                            </x:Arguments>
                    </viewModels:PlayerViewModel>
                </views:PlayerView.BindingContext>
            </views:PlayerView>
        </DataTemplate>
    </BindableLayout.ItemTemplate>
</FlexLayout>

但是PlayerModel始终为null。所以,我在模型上使用了biniding

            <viewModels:PlayerViewModel>
                <x:Arguments>
                        <x:Boolean>false</x:Boolean>
                        <models:PlayerModel 
                            PlayerName="{Binding Source={x:Reference playerscollection},Path=PlayerName}" 
                            PlayerPayment="{Binding Source={x:Reference playerscollection},Path=PlayerPayment}" 
                            Sports="{Binding Source={x:Reference playerscollection},Path=Sports}" />
                    </x:Arguments>
            </viewModels:PlayerViewModel>

它给出错误错配x:argument

0 个答案:

没有答案