【发布时间】:2013-07-12 09:48:33
【问题描述】:
我很难理解导航在 WP8 上的工作原理,我正面临这个问题:
假设我在一个单独的项目中有一个自定义控件,并且我在同一个项目中有一个控件设置页面。
结构如下:
CustomControlProject
|- CustomControl.xaml
|- CustomControlSettings.xaml
CustomControl 扩展了UserControl。
现在,我要做的是将一些数据传递给CustomControlSettings.xaml,我说的是一个复杂的对象(StackPanel)。
由于CustomControl 是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; 将获得MainPage 作为pg,这会导致异常,因为在与MainPage.xaml 相同的文件夹中没有DestinationPage.xaml。
Message "No XAML was found at the location '/DestinationPage.xaml'."
所以问题是:
如果我在项目 B 中有自定义控件和页面,如果我从项目 A 中引用项目 B,我如何将对象传递到页面并导航到该页面?
【问题讨论】:
标签: c# .net xaml navigation windows-phone-8