ListBox SelectedItem binded: page navigation, getting item, showing its properties in a new view and reset SelectedIndex. How can i do?
-
14-06-2021 - |
Domanda
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!
Soluzione
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
}
Altri suggerimenti
The best way is to have your collection stored somewhere you can access it anywhere (like in the Windows Phone Databound Application project) and pass the index of the selected item in your navigation uri
int index = recipesListBox.SelectedIndex;
this.NavigationService.Navigate(new Uri(destination +"?index="+index , UriKind.Relative));
Then in the OnNavigatedTo method of your new page get the index from the query and get the item
override OnNavigatedTo(
{
string index;
if(NavigationContext.QueryString.TryGetValue("index", index))
{
// get the item from your collection based on this index
}
}