We have a simple Xamarin app that has a List of items from which you can select one to pass to another View (to allow for purchase). We are using Xamarin Forms and the MVVM pattern.
Our List form has a command that invokes
private async Task Purchase(object parm)
{
Product theProduct = parm as Product;
string json = System.Text.Json.JsonSerializer.Serialize(theProduct);
await _navigationService.NavigateTo("///purchase", json);
}
to pass the Json representation of the item we wish to purchase. This calls our helper with this code.
public Task NavigateTo(string route, string data)
{
return Shell.Current.GoToAsync($"{route}?jsonparm={data}");
}
The problem is that we bind a property of the json-ized object to a label on the purchase form, but the form is rendered before the query is received.
Our ViewModel has these properties:
string _jsonParm;
public string JsonParm
{
get { return _jsonParm; }
set { _jsonParm = Uri.UnescapeDataString(value); }
}
Product _theProduct;
public Product TheProduct
{
get
{
if (_theProduct == null)
{
if (!string.IsNullOrWhiteSpace(JsonParm))
{
_theProduct = System.Text.Json.JsonSerializer.Deserialize<Product>(JsonParm);
OnPropertyChanged(nameof(TheProduct));
}
}
return _theProduct;
}
}
and the PurchaseViewModel class is decorated with this:
[QueryProperty("JsonParm", "jsonparm")]
class PurchaseViewModel : BaseViewModel
The View has a label like this:
<Label Text="{Binding TheProduct.Description}" />
My question is How do we get the value of Description to display when the view is first rendered?
The constructor for our PurchaseViewModel is executed before the QueryProperty has been received.
We know this because we set a breakpoint on the setter for TheProduct and it is null when the form is being painted.
We have a button on that form that executes a Command, and if we press the button, the OnPropertyChanged event is fired and our label magically gets populated.
We have searched Dr.Google and have not found this exact scenario, but it seems to us like a fairly common Master/Detail kind of problem.
To sum up:
- View_1 navigates to View_2 with a Json string of the current selected item.
- View_2 has a Label that must display the Description property of the Json object.
- View_2 does not seem to be able to resolve the QueryProperty until after it is rendered.
As usual, any help is appreciated.
Environment:
VS 2019
.Net Standard 2.1
Xamarin 16.9
** Slight edit on the suggested and accepted answer **
string _jsonParm;
public string JsonParm
{
get { return _jsonParm; }
set
{
_jsonParm = Uri.UnescapeDataString(value);
TheProduct = System.Text.Json.JsonSerializer.Deserialize<Product>(_jsonParm);
}
}
Product _theProduct;
public Product TheProduct
{
get { return _theProduct; }
set
{
_theProduct = value;
OnPropertyChanged(nameof(TheProduct));
}
}
Set the
TheProduct
property inside ofJsonParm
setter: