0

I have a page where I bind a command to a button. When I click it I calls a method where I get the data I want from an API.What if I don't want to only bind the data at the view but also use these data in code behind?! Lets say this is my view :

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="HelloWorld.Pages.JohnDoePage" xmlns:local="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Pages" xmlns:vm="clr-namespace:HelloWorld.ViewModel;assembly=HelloWorld"> <StackLayout Padding="20, 10" HorizontalOptions="Center"> <Button Command="{Binding JohnDoe}" Text="Data about John Doe" /> </StackLayout> </ContentPage> 

the code behihnd :

 Models.Info info; public JohnDoePage(Models.Info info) { InitializeComponent(); BindingContext = new InfoDetailsViewModel(info); this.info= info; // i want to use the data here //using the data } 

the view model :

 Data _data; public Data Data { get { return _data; } set { if (value == _data) return; _data = value; OnPropertyChanged(); } } public ICommand JohnDoe { get { return new Command(async () => { var Dataa = await _apiServices.InfoAboutJohnDOe(); }); } } 

and the service where I get the data I need is OK. I'm using the same viewmodel for binding different commands, and I don't know if this is possible by the way so I'm stuck. Any idea how can I use the data I get in the view code-behind?? Thanks in advance!!

2 Answers 2

1

why not just maintain a class level reference to your VM?

Models.Info info; InfoDetailsViewModel vm; public JohnDoePage(Models.Info info) { InitializeComponent(); vm = new InfoDetailsViewModel(info); BindingContext = vm; this.info= info; } 
Sign up to request clarification or add additional context in comments.

3 Comments

yeah, ok..but what about the data? Because vm = new InfoDetailsViewModel(info); the info are another data which I get from another command.
Just expose a Data property in your VM, then you can access it from the code-behind
of course. I already did that but I didn't get the right reference of the model in code-behind. Thanks for the answer :)
1

Save the result of your Service call as a public property

public <TargetType> Dataa { get; set; } 


and save the DataContext of your JohnDoePage as a member.

JohnDoePageViewModel dataContext = (JohnDoePageViewModel)this.DataContext; 


Because then you are able to get the information from the ViewModel.

var data = dataContext.Dataa; 


Does this help?

1 Comment

Hey Mark, a little to late, but I tried your solution and my app breaks. I think it happens because var data = dataContext.Dataa; this checks for the data before the button is tapped. Any idea on how to handle this?! :) @mark

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.