2012-11-05 46 views
8

我想在Windows 8平鋪應用程序中找到Numericbox的一個很好的替代方案。我嘗試使用與Windows窗體存在相同的數字框,但得到了一個錯誤,說這些不支持(?)由Windows 8應用程序。我注意到tile應用程序的TextBox元素有一個可以設置爲「Number」的InputScope,但它仍然允許用戶鍵入他想要的任何字符。我認爲InputScope不會做我認爲的事情。在Windows 8應用程序中的Numericbox的替代品?

我目前正在使用文本框進行管理,但由於我正在進行計算,所以文本必須不斷地轉換爲十進制,然後返回到文本,當我想更新界面時,除了必須執行幾次檢查以外確保用戶不輸入非數字字符。這變得非常單調乏味,並且非常熟悉Windows Form,這似乎是朝着錯誤方向邁出的一步。我必須錯過明顯的東西?

+0

'InputScope'用於觸摸輸入鍵盤類型。 – BrunoLM

回答

3

我不熟悉NumericTextBox,但這裏是一個簡單的C#/ XAML實現,它只允許數字和十進制字符。

它只是覆蓋OnKeyDown事件;基於被按下的鍵,它允許或不允許該事件到達基類TextBox類。

我應該注意到這個實現是針對Windows應用商店的應用 - 我相信你的問題是關於那種類型的應用,但我不是100%確定的。

public class MyNumericTextBox : TextBox 
{ 
    protected override void OnKeyDown(KeyRoutedEventArgs e) 
    { 
     HandleKey(e); 

     if (!e.Handled) 
      base.OnKeyDown(e); 
    } 

    bool _hasDecimal = false; 
    private void HandleKey(KeyRoutedEventArgs e) 
    { 
     switch (e.Key) 
     { 
      // allow digits 
      // TODO: keypad numeric digits here 
      case Windows.System.VirtualKey.Number0: 
      case Windows.System.VirtualKey.Number1: 
      case Windows.System.VirtualKey.Number2: 
      case Windows.System.VirtualKey.Number3: 
      case Windows.System.VirtualKey.Number4: 
      case Windows.System.VirtualKey.Number5: 
      case Windows.System.VirtualKey.Number6: 
      case Windows.System.VirtualKey.Number7: 
      case Windows.System.VirtualKey.Number8: 
      case Windows.System.VirtualKey.Number9: 
       e.Handled = false; 
       break; 

      // only allow one decimal 
      // TODO: handle deletion of decimal... 
      case (Windows.System.VirtualKey)190: // decimal (next to comma) 
      case Windows.System.VirtualKey.Decimal: // decimal on key pad 
       e.Handled = (_hasDecimal == true); 
       _hasDecimal = true; 
       break; 

      // pass various control keys to base 
      case Windows.System.VirtualKey.Up: 
      case Windows.System.VirtualKey.Down: 
      case Windows.System.VirtualKey.Left: 
      case Windows.System.VirtualKey.Right: 
      case Windows.System.VirtualKey.Delete: 
      case Windows.System.VirtualKey.Back: 
      case Windows.System.VirtualKey.Tab: 
       e.Handled = false; 
       break; 

      default: 
       // default is to not pass key to base 
       e.Handled = true; 
       break; 
     } 
    } 
} 

這是一些示例XAML。請注意,它假定MyNumericTextBox位於項目命名空間中。

<StackPanel Background="Black"> 
    <!-- custom numeric textbox --> 
    <local:MyNumericTextBox /> 
    <!-- normal textbox --> 
    <TextBox /> 
</StackPanel> 
+0

注意,這個例子不適合Shift +數字,所以它允許特殊字符通過,而且小數點只能被添加一次,如果被刪除則不能再次添加。 – Dave

相關問題