2011-09-29 121 views
2

我有一个没有绑定的文本框。输入验证Silverlight

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

该文本框只接受数字(双打),并立即显示其他信息(字母或符号)写入框中。

在TextChanged事件,我做取决于值照耀处一些计算并显示在一个TextBlock,为此我需要验证输入是一个号码作为用户在框中写的一些方法,但我有很难找到一个很好的方法来做到这一点。

任何想法?

回答

4

我之前使用的是一个正则表达式来禁止非数字字符。也许这是可以改编的东西?

我的代码是服务器上的端口,所以只有数字,但应该很直接地添加。双打(我觉得“[^ 0-9 \。]”应该工作,但regexs是不是我飞驰擅长:-))

// 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

也许这将更好地使用BindingValueConverter那将更新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 
    } 
} 

你真的不解释你想要的操作,当用户输入无效值时服用。