2014-10-07 80 views
2

我目前正試圖在我的應用程序中「跳轉到」菜單。我希望它看起來和工作的方式就像在谷歌設計書here頂部的一個,在那裏你在菜單中有該頁面的每個部分的字幕(準確地說,那個導航部分具有諸如內容,Baseline Grids,Keylines and Spacing等)。如果可能的話,我希望它能夠在不將其分割爲新的MVVM視圖的情況下工作,全部在一個UserControl內。是否有可能創建一些關鍵字,只需使用HTML中的「goto」鏈接製作菜單?跳轉到UserControl內導航

<a href="#metrics-and-keylines-baseline-grids">Baseline Grids</a> 

也許是一個自定義的ScrollViewer?但是,如何知道UI中每個元素的高度?

回答

2

每個框架元素都有一個BringIntoView方法。你可以定義一個超鏈接或按鈕菜單,無論它能夠調用一個命令。該命令將採取的元素作爲參數,並且命令執行將調用BringIntoView();

一個簡單的例子:

public class JumpToElementCommand : ICommand 
{ 
    public void Execute(object parameter) 
    { 
     FrameworkElement frameworkElement = parameter as FrameworkElement; 

     if (frameworkElement != null) 
     { 
      frameworkElement.BringIntoView(); 
     } 
    } 

    public bool CanExecute(object parameter) 
    { 
     return parameter is FrameworkElement; 
    } 

    public event EventHandler CanExecuteChanged 
    { 
     add { CommandManager.RequerySuggested += value; } 
     remove { CommandManager.RequerySuggested -= value; } 
    } 
} 

XAML用法:

<Window.Resources> 
<commands:JumpToElementCommand x:Key="JumpToElementCommand" /> 
</Window.Resources> 

<Button Command="{StaticResource JumpToElementCommand}" CommandParameter="{Binding ElementName=FirstJump}" /> 

<Grid x:Name="FirstJump"> 
</Grid> 

編輯:新增的CommandManager .RequerySuggested,以便在加載後重新評估命令參數。

+0

你有什麼想法,我怎麼能強制視圖顯示我想在頂部而不是'ScrollViewer'底部的項目? – mikes 2014-10-10 14:02:47

+1

@ mikes:看看這個:http://stackoverflow.com/questions/2946954/make-listview-scrollintoview-scroll-the-item-into-the-center-of-the-listview-c,你也可能是能夠在最後一個導航點上調用BringIntoView,然後在導航點上調用BringIntoView,只要導航的導航點位於最後一個導航點的上方。 – 2014-10-10 14:54:17

0

現在(在Michael G的大力幫助下)我有答案。 首先爲菜單製作一個ihnerited面板(對於我來說,它是父母ItemsControlStackPanel主人)。比訂閱ItemsControl中的按鈕項目的所有Click事件。作爲CommandParameter綁定到一個元素要跳轉到:

<Button CommandParameter="{Binding ElementName=jumpTarget}"/> 

而且在您使用Click事件處理程序的解決方案呈現here其中

Control_GotFocus(object sender, RoutedEventArgs e) 

istead您通過CommandParameter喜歡這裏:

Control_GotFocus(FrameworkElement targetControl) 

你還必須得到父母ScrollViewer並把它作爲AssociatedObject在上面的例子中( here解釋瞭如何獲取所選類型的父項)。當然,您可以通過簡單地使用帶有參數ItemsControl的每個Button添加參數的命令來避免事件subciption。