我正在尝试使用 MVVM Light 在我的应用程序中应用 MVVM 模式。我有一个数据绑定的列表框...
MainView.xaml [摘录]
<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" >
主视图模型.cs [摘录]
private Recipe selectedRecipe;
public Recipe SelectedRecipe
{
get
{
return selectedRecipe;
}
set
{
selectedRecipe = value;
RaisePropertyChanged("SelectedRecipe");
}
}
。在选择上执行页面导航已更改:
MainView.xaml.cs [摘录]
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)
}
在//之后,您可以看到在页面导航后重置索引的旧代码 - 现在,使用绑定数据,显然它也将我选择的项目设置为 null!返回时,如何导航到新视图,显示所选项目的属性并重置所选索引?谢谢!
我这样做的方式是这样的:
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
if (listBox.SelectedItem != null)
{
listBox.SelectedIndex = -1;
}
base.OnNavigatedFrom(e);
}
然后将以下内容添加到"选择已更改"事件
if(SelectedItem != null)
{
// Do something with SelectedItem
}
最好的方法是将集合存储在可以在任何位置访问它的位置(如在 Windows Phone 数据绑定应用程序项目中),并在导航 URI 中传递所选项的索引
int index = recipesListBox.SelectedIndex;
this.NavigationService.Navigate(new Uri(destination +"?index="+index , UriKind.Relative));
然后在新页面的 OnNavigatedTo 方法中从查询中获取索引并获取项目
override OnNavigatedTo(
{
string index;
if(NavigationContext.QueryString.TryGetValue("index", index))
{
// get the item from your collection based on this index
}
}