【问题标题】:Jump to navigation inside a UserControl跳转到 UserControl 内的导航
【发布时间】:2014-10-07 15:56:08
【问题描述】:

我目前正在尝试在我的应用程序中创建一个“跳转到”菜单。我希望它的外观和工作方式类似于顶部的谷歌设计书here 中的一个,您可以在菜单中找到该页面每个部分的字幕(准确地说,带有此类链接的导航部分如内容、基线网格、关键线和间距等)。如果可能的话,我希望它在不将其拆分为新的 MVVM 视图的情况下工作,所有这些都在一个 UserControl 中。是否可以创建一些关键字,然后只使用 HTML 中的“goto”链接制作菜单?

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

也许是自定义 ScrollViewer?但是如何知道 UI 中每个元素的高度呢?

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    每个框架元素都有一个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 以便在加载后重新评估命令参数。

    【讨论】:

    • 您知道如何强制视图在ScrollViewer 的顶部而不是底部显示我想要的项目吗?
    • @mikes:看看这个:stackoverflow.com/questions/2946954/…,你也可以在最后一个导航点调用 BringIntoView,然后在你的导航点调用 BringIntoView,只要你导航的导航点to 高于最后一个。
    【解决方案2】:

    现在(在 Michael G 的大力帮助下)我找到了答案。 首先为菜单制作一个 ihnerited 面板(对我来说,它是父 ItemsControlStackPanel 主机)。比订阅ItemsControl 内的按钮项的所有点击事件。作为 CommandParameter 绑定到您要跳转到的元素:

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

    在 Click 事件处理程序中,您使用 here 提供的解决方案,而不是

    Control_GotFocus(object sender, RoutedEventArgs e)
    

    你通过CommandParameter 喜欢这里:

    Control_GotFocus(FrameworkElement targetControl)
    

    您还必须获取父级ScrollViewer 并在上面的示例中将其设置为AssociatedObjecthere 解释了如何获取所选类型的父级)。当然,您可以通过简单地使用将参数添加到来自ItemsControl 的每个Button 的命令来避免事件订阅。

    【讨论】:

      猜你喜欢
      • 2016-09-21
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多