大家好我有一个列表框MainListBox
,其中我动态添加项目。
现在我想在列表框中选择一个项目时导航到DetialsPage.xaml.cs。
然后,我可以在那里显示有关所选项目的信息。
private void SetListBox()
{
foreach (ToDoItem todo in itemList)
{
MainListBox.Items.Add(todo.ToDoName);
}
}
MainListBox_SelectionChanged(“由visual studio 2010 silverlight for Windows 7手机生成)
// Handle selection changed on ListBox
private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// If selected index is -1 (no selection) do nothing
if (MainListBox.SelectedIndex == -1)
return;
// Navigate to the new page
NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative));
// Reset selected index to -1 (no selection)
MainListBox.SelectedIndex = -1;
}
DetailsPage.xaml.cs中的是下一个方法。 (“由visual studio 2010 silverlight for windows 7手机生成) 我知道下面的方法没有做我尝试的。
// When page is navigated to set data context to selected item in list
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string selectedIndex = "";
if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
{
int index = int.Parse(selectedIndex);
DataContext = App.ViewModel.Items[index];
}
}
我想访问selectedIndex并调用MainListbox中我的对象的方法 所以基本上: Mainlistbox => select item =>将该项目发送到详细信息页面=>详细信息页面访问项目和对项目(对象)的调用方法
我确信这是一个基本问题,很难找到任何细节。我想补充一点,这是我的第一个Windows Phone 7应用程序。
答案 0 :(得分:0)
答案很简单 - 您不能直接将对象传递给另一个页面。您可以将其序列化为JSON或XML,然后在目标页面上反序列化,但序列化项目仍然必须作为参数传递。
答案 1 :(得分:0)
您可以通过多种方式将对象从一个页面传递到另一个页面:
像Dennis所说的那样序列化和反序列化,但这虽然可行但是不实用,除非您想将对象保存在隔离存储中并稍后检索它。
将对象放在App.cs类中,所有页面都可以访问该类。在主页面中设置对象,从“详细信息”页面检索它。
放入App.cs的代码:MyObject selectedObject;
放入MasterPage.cs的代码:application.selectedObject = MainListBox.selectedItem;
放入DetailsPage.cs的代码:MyObject selectedObject = application.seletedObject;
答案 2 :(得分:0)
您可以发送对象或类似内容的ID,而不是将selectedindex作为查询字符串参数发送,这可以唯一地标识对象。
然后在详细信息页面中,您可以从主列表框从其获取数据的相同数据源中获取正确的对象(在您的情况下,“itemList”可能来自例如IsolatedStorage)。
如果itemList被实例化并仅保留在主页面中,那么您将无法从详细信息页面按ID获取项目。因此,在这种情况下,您需要将itemList移动到某个静态或应用级存储。
HTH