Reputation: 556
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (DataContext == null)
{
string selectedIndex = "";
if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
{
int index = int.Parse(selectedIndex);
DataContext = App.ViewModel.Items[index];
}
}
}
This is a code snippet from DetailsPage.xaml.cs in Windows phone databound app . please explain the working of this code block line by line .
Upvotes: 0
Views: 398
Reputation: 556
if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
what i can understand is that when page is loaded QueryString is loaded with instance of Dictionary class. Then using this instance TryGetValue method is called . Here selectedItem is the key of element in dicionary class , and the second parameter ensures that the method returns true only if and only if an element with key "selectedItem" is present in Dictionary class . OR if our query string supplied contains "selectedItem".
int index = int.Parse(selectedIndex);
Selected Index contains value associated with that key but it is in string hence using parse method of int class we convert it into integer type and store it in index variable.
DataContext = App.ViewModel.Items[index];
Then the DataContext of DetailPage is set to the object in collection Items located at position equal to index .
Upvotes: 0
Reputation: 89285
Check this out, explanation goes under line of code being explained :
if (DataContext == null)
Setup DataContext only if it is currently null (has not been set).
if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
Try to get query string parameter value having parameter key = "selectedItem". If such parameter exists in query string, TryGetValue
function will return true
, otherwise it'll return false
. Therefore, next 2 line of codes will only be executed if "selectedItem" parameter supplied in query string.
int index = int.Parse(selectedIndex);
parse string value from selectedIndex
to an integer value.
DataContext = App.ViewModel.Items[index];
set DataContext
of DetailsPage to an object stored in Items
property at index = index
.
.
Upvotes: 1