HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Navigating to a view

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
viewnavigatingstackoverflow

Problem

I'm navigating to a view. I have an EventDateTime property which I want to set to DateTime.Today unless the navigation is coming from MyCustomView

This is what I've come with so far. It's working, but I find this really ugly:

public void OnNavigatedTo(NavigationParameters parameters)
{
    if (parameters != null)
    {
        if (!parameters.ContainsKey(PARAM_NAVIGATEDFROM)) // If there is parameter PARAM_NAVIGATEDFROM, then the navigation doesn't come from MyCustomView
        {
            EventDateTime = DateTime.Today;
        }
        else if (parameters[PARAM_NAVIGATEDFROM] != typeof(MyCustomViewModel)) // If there is a parameter PARAM_NAVIGATEDFROM but not with the specific value, the navigation doesn't come from MyCustomView
        {
            EventDateTime = DateTime.Today;
        }
    }
    else // If there are no parameters at all, the navigation is not coming from MyCustomView either
    {
        EventDateTime = DateTime.Today;
    }
}


Any ideas how I can improve this Code? Maybe even with another approach instead of putting the Code into the OnNavigatedTo() method?

Solution

I think Bethan has the best approach, but you could take it one step further and use a generic Type:

public void OnNavigatedTo(NavigationParameters parameters)
{
if (!IsNavigationFrom(parameters))
{
EventDateTime = DateTime.Today;
}
}

private bool IsNavigationFrom(NavigationParameters parameters)
{
return parameters != null
&& parameters.ContainsKey(PARAM_NAVIGATEDFROM)
&& parameters[PARAM_NAVIGATEDFROM] == typeof(T);
}


This makes the method applicable to multiple view models.

Context

StackExchange Code Review Q#151743, answer score: 6

Revisions (0)

No revisions yet.