Search code examples
c#uwptuplestemplate10c#-7.0

Tuple<ThisThing, bool> parameter for OnNavigatedToAsync in Template 10


Should I be able to pass a Tuple as a parameter to OnNavigatedToAsync? Is there a better way to pass this kind of information?

I've tried this, but I keep getting an invalid cast exception in the Value = line below. Value is typed as Tuple<ThisThing, bool>

ViewModel.cs:

public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState)
{
        Value = (Tuple<ThisThing, bool>)((suspensionState.ContainsKey(nameof(Value))) ? suspensionState[nameof(Value)] : parameter);
}

Passing parameter as a Tuple.

public void GoToDetailsPage() =>
        NavigationService.Navigate(typeof(ThisThingPage), (new ThisThing() { Prop1=1, Prop2=2}, true));

Edit1: I've already tried simplifying this to

public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState)
{
    Value = (Tuple<ThisThing, bool>)parameter;
}

and when debugging and stepping into OnNavigatedToAsync, and hovering over parameter I can see that it is what I expect, a Tuple, but results in an InvalidCastException on the next line.


Solution

  • The issue here is that C# 7.0 tuples are not System.Tuple, they're System.ValueTuple. So the correct cast is:

    Value = (ValueTuple<ThisThing, bool>)parameter;
    

    Or using the tuple syntax:

    Value = ((ThisThing, bool))parameter;