2013-04-29 3 views
0

TextChangedEventArgs를 사용하여 텍스트 상자를 동적으로 생성하여 텍스트 상자에 숫자와 소수점 만 입력하도록 제한했습니다. 다음 는 C#을c : e.keychar 대신 wpf 속성

const char Delete = (char)8; 
if (Char.IsDigit(e.KeyChar)) 
{ 
    e.Handled = false; 
} 
else if (e.KeyChar == Delete) 
{ 
    e.Handled = false; 
} 
else if (e.KeyChar == '.') 
{ 
    if (!(amt.Text.Contains("."))) 
     e.Handled = false; 
    else 
    { 
     e.Handled = true; 
    } 
} 
else 
{ 
    e.Handled = true; 
} 

의 코드입니다하지만 WPF에서 이것을 사용할 수 없습니다.

e.key 또는 e.Text를 사용하여 코드를 변경하려고했습니다. 그러나이 두 가지를 사용할 수 없습니다. 다음 오류가 표시됩니다. 어셈블리 또는 지시문이 누락되었습니다.

제발 도와주세요.

+0

다시 MVVM을 배우고 절차 용 코드로 전체 UI를 만드는 것을 중단해야합니다. 그것이 바로 XAML입니다. WPF 및 기타 모든 XAML 기반 프레임 워크는 근본적으로 기존의 전통적 프레임 워크와는 다르기 때문에 작업 할 때 다른 사고 방식이 필요합니다. –

+0

가능한 [WPF TextBox 변경 이벤트 취소] 중복 (http://stackoverflow.com/questions/335129/cancelling-a-wpf-textbox-changed-event) –

답변

2
// one solution for filtering characters in a textbox.  
    // this is the PreviewKeyDown handler for a textbox named tbNumerical 
    // Need to add logic for cancelling repeated decimal point and minus sign 
    // or possible notation like 1.23e2 == 123 
    private void tbNumerical_PreviewKeyDown(object sender, KeyEventArgs e) 
    { 
     System.Windows.Input.Key k = e.Key; 

     // to see the key enums displayed, use a textbox or label 
     // someTextBox.Text = k.ToString(); 

     // filter out control keys, not all are used, add more as needed 
     bool controlKeyIsDown = Keyboard.IsKeyDown(Key.LeftShift);  

     if (!controlKeyIsDown && 
      Key.D0 <= k && k <= Key.D9 || 
      Key.NumPad0 <= k && k <= Key.NumPad9 || 
      k == Key.OemMinus || k == Key.Subtract || 
      k == Key.Decimal || k == Key.OemPeriod) // or OemComma for european decimal point 

     else 
     { 
      e.Handled = true; 

      // just a little sound effect for wrong key pressed 
      System.Media.SystemSound ss = System.Media.SystemSounds.Beep; 
      ss.Play(); 

     } 
    }