Post Impatica
Post Impatica

Reputation: 16463

Xamarin.Forms - Pass a value from View to ViewModel

Anyone know how to pass a random string value to the viewmodel from within the view's code-behind in Xamarin.Forms?

  1. The string value doesn't come from any of the controls being displayed to the user.

  2. The value is not available until well after the page is displayed to the user.

  3. The value is only available to me to consume from within the view, not the viewmodel.

Upvotes: 2

Views: 5059

Answers (4)

Mario Ariyanto
Mario Ariyanto

Reputation: 326

Continuing from WoeliJ's answer, for those who want to pass a button parameter from view to viewmodel. In the sample below, I'm passing a button text to some variable in the view model.

private void *Clicked Event* (object sender, EventArgs e)
{
   ((*YourViewModel*)this.BindingContext).*SomeVarInViewModel* = ((Button)sender).Text as string;
}

Upvotes: 0

Venkata Swamy Balaraju
Venkata Swamy Balaraju

Reputation: 1481

Maybe MessagingCenter concept will useful for you

https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/messaging-center/

Upvotes: 0

woelliJ
woelliJ

Reputation: 1504

You can do it by accessing your ViewModel through the BindingContext of your View like so:

((ViewModelType)this.BindingContext).SomeProperty = "someRandomString"

Upvotes: 9

MojoFilter
MojoFilter

Reputation: 12296

Sounds like you could just make a property or a method on the view model to accept the value.

public string APropertyToSet {get; set;}
public void SetSomeValueFromTheView(object value) {}

Upvotes: 0

Related Questions