i'm trying to apply the MVVM pattern in my application with MVVM Light. I've a databinded ListBox...
MainView.xaml [extract]
<ListBox Name="recipesListBox"
ItemsSource="{Binding RecipeList}"
SelectedItem="{Binding SelectedRecipe, Mode=TwoWay}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Grid.Row="1"
Margin="12,0,12,0"
SelectionChanged="recipesListBox_SelectionChanged" >
MainViewModel.cs [extract]
private Recipe selectedRecipe;
public Recipe SelectedRecipe
{
get
{
return selectedRecipe;
}
set
{
selectedRecipe = value;
RaisePropertyChanged("SelectedRecipe");
}
}
...that performs a page navigation on SelectionChanged:
MainView.xaml.cs [extract]
private void recipesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string destination = "/RecipeView.xaml";
if (recipesListBox.SelectedIndex == -1) // If selected index is -1 (no selection) do nothing
return;
this.NavigationService.Navigate(new Uri(destination, UriKind.Relative));
//recipesListBox.SelectedIndex = -1; // Reset selected index to -1 (no selection)
}
After // you can see the old code that reset the index after page navigation - now, with binded data, obviously it also set null my selected item! How can i do for navigate to a new view, show the property of selected item and reset the selected index when i go back? Thank you!
The way I did it was this:
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
if (listBox.SelectedItem != null)
{
listBox.SelectedIndex = -1;
}
base.OnNavigatedFrom(e);
}
then add the following to SelectionChanged event
if(SelectedItem != null)
{
// Do something with SelectedItem
}