2010-04-26 57 views
3

我看到有幾個人遇到了問題,所以我想發佈一個我在處理這個問題時提出的(有點)優雅的解決方案。問題是在Silverlight中創建模板頁面時,ContentControls沒有父框架的NavigationService(當您嘗試使用它時,它始終爲空)。 NavigationService存在於intellisence中的情況類似,但始終爲空。爲了使整個網站的導航:Silverlight NavigationService總是空的

  1. 創建一個新的UserControl(我叫我的「NavFrame」),其中有一個導航框(我叫我的「RootFrame」)。

  2. 在這個框架內,你可以設置你喜歡的任何內容。

  3. 在App.xaml.cs中設置此UserControl爲RootVisual(即this.RootVisual = new NavFrame();)。

  4. 要使用的NavigationService在任何網頁上,你可以輸入類似:

    ((NavFrame)App.Current.RootVisual).RootFrame.NavigationService 
        .Navigate(new Uri("Your Uri", UriKind.RelativeOrAbsolute)); 
    
+0

+1:一直在尋找讓我能夠使用App.Xaml.cs類中的NavigationService的東西。謝謝。 – 2010-08-25 15:38:41

回答

0
((Frame)(Application.Current.RootVisual as MainPage).FindName("ContentFrame")) 
    .Navigate(new Uri("Page Name", UriKind.Relative)); 
1

您可以創建一個動作並拖動它放在控制上面你想導航發生,就像這樣:

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

現在,你只需要它和電線將其拖動到你的目標PA GE。順便說一句,對於SL4來說這是真的,從來沒有在SL3上嘗試過。並且URI的工作形式爲:「/SilverlightApplication1;component/Page1.xaml」或在框架上使用UriMapping。