Silvelright -set tabindex of UIElements in MVVM



我正在尝试在用户控件中设置两个UIElement的选项卡索引。用户控件包含一个文本框和按钮。我目前通过附加属性将焦点应用于文本框,但是我希望能够按 Tab 键并从文本块导航到按钮或检测按键(Enter 键)并触发按钮上的命令(我知道单独的问题)

主要重点是首先完成选项卡索引。

感谢您的任何指示或建议。

更新

此后,我尝试使用附加属性来处理制表符顺序

        public static DependencyProperty TabIndexProperty = DependencyProperty.RegisterAttached("TabIndex", typeof(int), typeof(AttachedProperties), null);
    public static void SetTabIndex(UIElement element, int value)
    {
        Control c = element as Control;
        if (c != null)
        {
            RoutedEventHandler loadedEventHandler = null;
            loadedEventHandler = new RoutedEventHandler(delegate
                {
                    HtmlPage.Plugin.Focus();
                    c.Loaded -= loadedEventHandler;
                    c.Focus();
                });
            c.Loaded += loadedEventHandler;
        }
    } 

但是,当我尝试编译时,我收到按钮控件不存在 TabIndex 属性的错误。任何想法为什么会失败?

这是一个特定于视图的问题,因此,即使在 MVVM 中也应该在 ViewLevel 处理。MVVM 没有规定从代码隐藏中删除所有代码。这只是意味着当您将代码放在那里时,您应该有一个特定于视图的关注点。这是其中一种情况,imo。

天色已晚...我使用附加属性解决了这个问题。在上面的解决方案中,我复制了我创建的早期 DP,并且在测试之前没有更改代码。

以下是工作解决方案

我创建了一个附加的属性类,然后添加了以下代码:

       #region Search Field Focus
    public static DependencyProperty InitialFocusProperty = DependencyProperty.RegisterAttached("InitialFocus", typeof(bool), typeof(AttachedProperties), null);
    public static void SetInitialFocus(UIElement element, bool value)
    {
        Control c = element as Control;
        if (c != null && value)
        {
            RoutedEventHandler loadedEventHandler = null;
            //set focus on control
            loadedEventHandler = new RoutedEventHandler(delegate
                {
                HtmlPage.Plugin.Focus();
                c.Loaded -= loadedEventHandler;
                c.Focus();
            });
            c.Loaded += loadedEventHandler;
        }
    }
    public static bool GetInitialFocus(UIElement element)
    {
        return false;
    }
    #endregion
    #region Tabbing Order of Elements
    public static DependencyProperty TabIndexProperty = DependencyProperty.RegisterAttached("TabIndex", typeof(int), typeof(AttachedProperties), null);
    public static void SetTabIndex(UIElement element, int value)
    {
        element.SetValue(TabIndexProperty, value);
    }
    public static int GetTabIndex(UIElement element)
    {
        return (int)element.GetValue(TabIndexProperty);
    }
    #endregion

第一个 DP 设置文本块的焦点,以便在加载用户控件时看到光标放置在文本字段中。

DP 2 设置制表符顺序。由于焦点已经应用于当前控制制表符正常到位。如果您没有关注控件,则需要先设置此设置。

最后在 XAML 中在 XMLN 中声明您的类并添加到控件中。

最新更新