C# silverlight,列表框导航到新页面,是否可能使用对象?

C# silverlight,列表框导航到新页面,是否可能使用对象?,c#,silverlight,silverlight-4.0,windows-phone-7,C#,Silverlight,Silverlight 4.0,Windows Phone 7,大家好,我有一个列表框MainListBox,我在其中动态添加项目。 现在,当我在列表框中选择一个项目时,我想导航到DetialsPage.xaml.cs。 然后,我可以在其中显示有关所选项目的信息 private void SetListBox() { foreach (ToDoItem todo in itemList) { MainListBox.Items.Add(todo.ToDoName); } } MainListBox_选择已更改(“由v

大家好,我有一个列表框
MainListBox
,我在其中动态添加项目。 现在,当我在列表框中选择一个项目时,我想导航到DetialsPage.xaml.cs。 然后,我可以在其中显示有关所选项目的信息

private void SetListBox()
{
    foreach (ToDoItem todo in itemList)
    {
        MainListBox.Items.Add(todo.ToDoName);
    }
}
MainListBox_选择已更改(“由visual studio 2010 silverlight为windows 7 phone生成)

详细地说,spage.xaml.cs是下一个方法。(“由visual studio 2010 silverlight for windows 7 phone生成) 我知道下面的方法不符合我的尝试

// 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=>send the item to details page=>details page访问该项并调用该项(对象)上的方法


我相信这是一个基本的问题,很难找到任何细节。我想补充一点,这是我的第一个windows phone 7应用程序。

这里的答案很简单-你不能直接将对象传递到另一个页面。您可以将其序列化为JSON或XML,然后在目标页面上对其进行反序列化,但序列化的项仍必须作为参数传递。

可以通过多种方式在页面之间传递对象:

  • 像Dennis所说的那样进行序列化和反序列化,但这虽然可行,但并不实用,除非您希望将对象保存在独立存储中并在以后检索它

  • 在App.cs类中放置一个对象,该类可供所有页面访问。在母版页中设置对象,然后从详细信息页中检索它

  • 放入App.cs的代码:MyObject selectedObject

    放入MasterPage.cs的代码:application.selectedObject=MainListBox.selectedItem

    放入DetailsPage.cs的代码:MyObject selectedObject=application.selectedObject

  • 您可以在LayoutRoot的DataContext中设置该对象,但我手头上没有这方面的代码

  • 您可以发送对象或类似对象的ID,而不是将selectedindex作为查询字符串参数发送,该ID可以唯一地标识对象

    然后,在详细信息页面中,您可以从主列表框获取其数据的同一数据源中获取正确的对象(在您的示例中,“itemList”可能来自例如IsolatedStorage)

    如果itemList被实例化并仅保存在主页内,那么您将无法从详细信息页面按ID获取项目。因此,在这种情况下,您需要将itemList移动到一些静态或应用程序级存储

    // 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];
        }
    }