Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a parameter from one Page to another Page in Xamarin.Forms?

I want to send a value when I press a button in a form to another form through the MVVM pattern.

This is the XAML file

 <Button x:Name="myButton"
            Text="RandomButton"
            TextColor="#000000"
            BackgroundColor="{x:Static local:FrontEndConstants.ButtonBackground}"
            Grid.Row="2" Grid.Column="0"
            Grid.ColumnSpan="3"
            Command="{Binding NewPage}"
            CommandParameter="100">     
</Button>

And this is my ModelView class where I get redirected to another form.

class JumpMVVM :INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private INavigation _navigation;

        public ICommand NewPage
        {
            get
            {
                return new Command(async () =>
                { 
                    await _navigation.PushAsync(new Page2()); // HERE
                });
            }
        }

        public JumpMVVM() { }

        public JumpMVVM(INavigation navigation)
        {                
            _navigation = navigation;                
        }

The jump works. How can I send that "CommandParameter" to "Page2" ?

Thanks, Dragos

like image 412
Dragos Avatar asked Feb 02 '15 13:02

Dragos


People also ask

How do you pass parameter to Viewmodel in xamarin forms?

If you want to transfer Guid to viewmodel, you need to implementing the IQueryAttributable interface on the AssignmentViewModel . It is achieved by appending ? after a route, followed by a query parameter guid, =, and a value. For example, you navigate method like following code.

What is messaging center in xamarin forms?

The Xamarin. Forms MessagingCenter class implements the publish-subscribe pattern, allowing message-based communication between components that are inconvenient to link by object and type references.


2 Answers

The easiest approach would be to pass the value as a parameter to the constructor of Page2. Or you could create a public property on Page2 and assign the value to it after you create it.

await _navigation.PushAsync(new Page2(argument_goes_here)); // HERE
like image 177
Jason Avatar answered Nov 04 '22 09:11

Jason


Use SQLite to store the object and instantiate it in the new ViewModel or use the messaging center built into Xamarin.Forms to pass data between ViewModels indirectly.

Jason's approach will work but personally passing data up to the view, to another view then back down to the view model is not something I want to do.

SQLite Documentation

http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/databases/

Messaging Center Documentation

http://developer.xamarin.com/guides/cross-platform/xamarin-forms/messaging-center/

like image 32
ClintL Avatar answered Nov 04 '22 11:11

ClintL