0

我正在努力理解导航在 WP8 上的工作原理,我正面临这个问题:

假设我在一个单独的项目中有一个自定义控件,并且我在同一个项目中有一个控件设置页面。

所以这是结构:

CustomControlProject
                    |- CustomControl.xaml
                    |- CustomControlSettings.xaml

CustomControl 扩展了UserControl.

现在,我想做的是将一些数据传递给CustomControlSettings.xaml并且我正在谈论一个复杂的对象(a StackPanel)。

因为CustomControl是 a UserControl,所以我没有NavigationService,所以我正在使用这段代码(我在 stackoverflow 上找到了它,但我丢失了选项卡):

    /// <summary>

    /// Walk visual tree to find the first DependencyObject  of the specific type.

    /// </summary>

    private DependencyObject GetDependencyObjectFromVisualTree(DependencyObject startObject, Type type)
    {

        //Walk the visual tree to get the parent(ItemsControl)

        //of this control

        DependencyObject parent = startObject;

        while (parent != null)
        {

            if (type.IsInstanceOfType(parent))

                break;

            else

                parent = VisualTreeHelper.GetParent(parent);

        }

        return parent;

    }

这样我就可以了

Page pg = GetDependencyObjectFromVisualTree(this, typeof(Page)) as Page;
pg.NavigationService ...

传递一个复杂的对象需要其他东西,所以我按照这里的说明操作:http: //www.sharpregion.com/easy-windows-phone-7-navigation/

这最终得到了一个像这样的导航方法:

base.OnTap(e);
Page pg = GetDependencyObjectFromVisualTree(this, typeof(Page)) as Page;
NavigationExt.Navigator.Navigate<DestinationPage>(pg.NavigationService, objectToPass);

发生的事情是我在另一个项目中使用这个控件,作为MainPage.xaml.

这应该意味着Page pg = GetDependencyObjectFromVisualTree(this, typeof(Page)) as Page;将获得MainPageaspg并且这会导致异常,因为DestinationPage.xaml在同一文件夹中没有MainPage.xaml.

    Message "No XAML was found at the location '/DestinationPage.xaml'."

所以问题是:

如果我在项目 B 中有一个自定义控件和一个页面,如果我从项目 A 中引用项目 B,我如何将一个对象传递给该页面并导航到该页面?

4

1 回答 1

1

查看您的问题和代码,我了解您希望在用户控件中点击某些元素时导航到页面。页面和用户控件都位于与主项目不同的项目中。

由于您的用户控件将托管在主项目的某个页面中,因此导航时的 URI 应如下所示:

/{assemblyName};component/{relativePath}

现在,NavigationService内部不可用,UserControl但您可以使用Application.RootVisual

base.OnTap(e);
var frame = Application.Current.RootVisual as PhoneApplicationFrame;
frame.Navigate(new Uri("/CustomControlProject;component/CustomControlSettings.xaml",
       UriKind.Relative));

对于将对象传递给页面,有很多方法。其中之一是利用PhoneApplicationService.

你可以这样做:

base.OnTap(e);
MyObjectType objectToPass = new MyObjectType();
PhoneApplicationService.Current.State["myObject"] = objectToPass;
var frame = Application.Current.RootVisual as PhoneApplicationFrame;
frame .Navigate(new Uri("/CustomControlProject;component/CustomControlSettings.xaml",
    UriKind.Relative));

// In destination page's constructor
public CustomControlSettings() {
  var myObject = (MyObjectType) PhoneApplicationService.Current.State["myObject"];
  // ...
}
于 2013-07-12T16:02:30.763 回答