问题描述
我读到一些人对此有疑问,所以我想发布一个(有些)优雅的解决方案,我试图解决这个问题.问题是,当您在Silverlight中创建模板页面时,ContentControls没有父Frame的NavigationService(尝试使用它时始终为null).在类似情况下,NavigationService以智能方式提供,但始终为null.要启用网站范围的导航,请执行以下操作:
I read that a few people were having a problem with this so I wanted to post a (somewhat) elegant solution I came up with while trying to deal with this. The problem is when you create templated pages in Silverlight and the ContentControls do not have the parent Frame's NavigationService (it's always null when you try and use it). There are similar scenarios where a NavigationService is present in intellisence but is always null. To enable site-wide Navigation:
-
创建一个新的
UserControl
(我叫我的'NavFrame'),其中有一个导航框架(我叫我的"RootFrame").
Create a new
UserControl
(I called mine 'NavFrame') that has a Navigation Frame in it (I called mine 'RootFrame').
在此框架内,您可以设置任何喜欢的内容.
Inside this Frame you can set whatever content you like.
将此用户控件设置为App.xaml.cs中的RootVisual
(即this.RootVisual = new NavFrame();
).
Set this UserControl as your RootVisual
in App.xaml.cs (i.e. this.RootVisual = new NavFrame();
).
要在您的任何页面中使用NavigationService,您可以输入以下内容:
To use the NavigationService in any of your pages you can type something like:
((NavFrame)App.Current.RootVisual).RootFrame.NavigationService
.Navigate(new Uri("Your Uri", UriKind.RelativeOrAbsolute));
推荐答案
您可以创建一个动作并将其拖动到要进行导航的控件上方,就像这样:
You can create an Action and drag it on top of the control you want to make navigation happen, just like this one:
public class NavigateAction : TriggerAction<DependencyObject>
{
public Uri Uri
{
get;
set;
}
protected override void Invoke(object parameter)
{
var frame = FindContainingFrame(AssociatedObject);
if(frame == null)
throw new InvalidOperationException("Could not find the containing Frame in the visual tree.");
frame.Navigate(Uri);
}
protected static Frame FindContainingFrame(DependencyObject associatedObject)
{
var current = associatedObject;
while(!(current is Frame))
{
current = VisualTreeHelper.GetParent(current);
if(current == null)
return null;
}
return (Frame)current;
}
}
现在,您只需要拖动它并将其连接到您的目标页面即可.顺便说一句,这对于SL4是正确的,从来没有在SL3上尝试过.并且URI的形式为:"/SilverlightApplication1;component/Page1.xaml "或在框架上使用UriMapping.
Now you just have to drag it and wire it to your target page. BTW this is true for SL4, never tried it on SL3. and the URI does work in the form: "/SilverlightApplication1;component/Page1.xaml" or with UriMapping on the Frame.
这篇关于Silverlight NavigationService始终为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!