user12935066
user12935066

Reputation:

Pass an argument from viewmodel to a page's ctor via TabBar Xaml?

I'm using Xamarin Form's Shell to create three tabs on the bottom of the page. One of the page's is accepting an argument which suppose to come from the MainViewModel (The design before was that the Page's icon was in the main screen and I would PushAsync and pass the argument by ctor, plain simple). But since I redesigned the app to use Shell and Tab's I do not know how to pass the page's ctor the argument from MainViewModel via xaml.

Any help would be appreciate, thanks.

<!--<ShellItem>
    <ShellContent>
        <pages:MainView/>
    </ShellContent>
</ShellItem>-->

<TabBar>
    <Tab Title="Main" Icon="mainscreen.png">
        <ShellContent>
            <pages:MainView/>
        </ShellContent>
    </Tab>

    <Tab Title="News" Icon="googlenews.png">
        <ShellContent>
            <pages:NewsView/>
        </ShellContent>
    </Tab>

    <Tab Title="Search" Icon="search.png">
        <ShellContent>
            <pages:SearchView> // need to pass this page an argument from MainViewModel
                <x:Arguments>
                    <vm:MainViewModel ListViewItems=""></vm:MainViewModel>
                </x:Arguments>
            </pages:SearchView>
        </ShellContent>
    </Tab>
</TabBar>
 public partial class SearchView : ContentPage
{
    public SearchView(ObservableCollection<DailyIRD> dailyIrd)
    {
        InitializeComponent();

        BindingContext = new SearchViewModel(this, dailyIrd);
    }
}

Upvotes: 0

Views: 326

Answers (1)

Wendy Zang - MSFT
Wendy Zang - MSFT

Reputation: 10978

I create a MainViewModel with Title property to test. The way below works well.

MainViewModel.cs

 public class MainViewModel  
{
    public string Title { get; set; } = string.Empty;
    public MainViewModel()
    {
        Title = "MainViewModel";
    }
}

AppShell.xaml:

    <Tab Title="Search" Icon="monkeyicon.png">
        <ShellContent>
            <local:SearchView>
                <local:SearchView.BindingContext>
                    <vm:MainViewModel />
                </local:SearchView.BindingContext>
                <!--  // need to pass this page an argument from MainViewModel  -->
                <!--<x:Arguments>
                    <vm:MainViewModel Title="{Binding .}" />
                </x:Arguments>-->
            </local:SearchView>
        </ShellContent>
    </Tab>

SearchView.xaml:

 <ContentPage.Content>
    <StackLayout>
        <Label
            HorizontalOptions="CenterAndExpand"
            Text="Welcome to SearchView!"
            VerticalOptions="CenterAndExpand" />

        <Label Text="{Binding Title}" />
    </StackLayout>
</ContentPage.Content>

Upvotes: 1

Related Questions