2011-09-29 11 views
2

나는 바인딩되지 않은 텍스트 상자가 있습니다.입력 유효성 검사 Silverlight

<TextBox x:Name="inputBox" Grid.Column="1" Grid.Row="1" /> 

텍스트 박스는 숫자 만 (더블)을 수용하고 뭔가 다른 일단 (문자 또는 기호)를 상자에 기록에서 경고를 표시하는 것입니다.

TextChanged 이벤트에서 enterd 값에 따라 계산을 수행하고 TextBlock에 표시하므로 사용자가 입력란에 숫자를 입력했는지 확인할 수있는 방법이 필요하지만 이것을하기에 좋은 길을 찾는 것이 힘들다.

아이디어가 있으십니까?

답변

4

내가 전에 사용했던 것은 숫자가 아닌 문자를 허용하지 않는 정규식입니다. 어쩌면 이것이 적응 될 수있는 것일까요?

내 코드는 서버의 포트 번호이므로 번호 만 입력하면됩니다. 복식에 대한 (내 생각 "[^ 0-9 \.]"작동하지만 정규식 등에서 특정 요소를 뽑아 오기 내가 :-)에서 환상적으로 좋은 생각 일 수 없습니다한다)

// Text change in Port text box 
private void txtPort_TextChanged(object sender, TextChangedEventArgs e) 
{ 
    // Only allow numeric input into the Port setting. 
    Regex rxAllowed = new Regex(@"[^0-9]", RegexOptions.IgnoreCase); 

    txtPort.Text = rxAllowed.Replace(txtPort.Text, ""); 
    txtPort.SelectionStart = txtPort.Text.Length; 
} 
1

어쩌면 ValueConverterBinding를 사용하는 것이 더 좋을 것이라고 TextBlock의 내용을 업데이트합니다. 이 경우 변환기 내에서 숫자 값에 대한 유효성 검사를 구현할 수 있습니다.

2

이것은 행동을 사용하는 또 다른 예입니다.

public class TextBoxValidator : Behavior<TextBox> 
{ 
    protected override void OnAttached() 
    { 
    AssociatedObject.TextChanged += new TextChanged(OnTextChanged); 
    } 

    private void OnTextChanged(object sender, TextChangedEventArgs e) 
    { 
    // Here you could add the code shown above by Firedragon or you could 
    // just use int.TryParse to see if the number if valid. 
    // You could also expose a Regex property on the behavior to allow lots of 
    // types of validation 
    } 
} 

사용자가 잘못된 값을 입력했을 때 수행 할 작업을 실제로 설명하지 않았습니다.

관련 문제