Search code examples
xamlxamarinxamarin.formsviewmodel

Add Complex argument for viewmodel constructor in XAML


There is bindable Item source of Flexlayout

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

Items in the viewmodel are defined as

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

FlexLayout datatemplate is a content view I need to assign a specific viewmodel "PlayerViewModel" as the content view BindingContext

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

So in FlexLayout,

<FlexLayout x:Name="playerscollection" Wrap="Wrap" BindableLayout.ItemsSource="{Binding Players}">
                                            <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>
</FlexLayout>

But the error says "Type 'PlayerViewModel' is not usable as an object element because it is not public or does not define a public parameterless constructor or a type converter"


Solution

  • I've created a basic demo to test the code and reproduce the error. The error doesn't affect the project build, it's just an intellisense error of the IDE. Please ignore the error and deploy the code, it'll work fine.