2011-05-10 68 views
0

我試圖在用戶控件中設置兩個UIElement s的tab索引。用戶控件包含一個文本框和按鈕。我目前通過附加屬性將焦點應用於文本框,但是我希望能夠按Tab鍵並從Textblock導航到按鈕或檢測按下按鍵(回車鍵)並觸發按鈕上的命令(我知道單獨的問題)Silvelright -set MVVM中UIElements的tabindex

主要關注點是首先完成標籤索引。

感謝您的任何指示或建議。

UPDATE

因爲我已經嘗試使用附加屬性來處理Tab鍵順序

 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屬性不存在爲按鈕控制。任何想法,爲什麼這是失敗?

回答

0

現在已經很晚了...我使用附加屬性解決了這個問題。在上述解決方案中,我複製了之前創建的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中聲明你的類在xmlns中並添加到控件中。

2

這是一個視圖特定的問題,因此,即使在MVVM中也應該在ViewLevel中處理。 MVVM不會規定您從後面的代碼中移除所有代碼。它只是意味着當你把代碼放在那裏時你應該特別關注視圖。這是其中的一種情況,即imo。

+0

我完全同意Scott和我聽到其他人的聲音相同,如果代碼是特定於視圖,它可以在後面的視圖代碼中處理。 – rlcrews 2011-05-10 21:13:10

+0

那麼,爲什麼你要使用附加屬性來代替文本框/按鈕的TabIndex屬性呢? – 2011-05-10 21:47:31

+0

從我發現,用戶控件如何初始化(在視圖中加載時)「防止」在xaml中設置TabIndex屬性。使用關聯屬性是我在這個異常中找到的解決方案(至少在MVVM項目中)。 – rlcrews 2011-05-11 03:54:07