我对编程非常陌生,主要是作为一种业余爱好,但我已经制作了一些小的可执行程序来帮助我完成我的工作(小行业特定的计算器。
关于这个问题,我有一个文本框,其内容显示在焦点之前,我想保留,但我也想只允许输入数字,有没有办法做到这一点。
答案 0 :(得分:1)
尝试将PreviewTextInput
事件处理程序添加到TextBox
。
textBox1.PreviewTextInput += new TextCompositionEventHandler(textBox1_PreviewTextInput);
在事件处理程序测试中,如果输入的字符是数字。
private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!char.IsDigit(e.Text, e.Text.Length - 1))
e.Handled = true;
}
答案 1 :(得分:0)
如果您想避免使用代码隐藏,可以通过创建包含AttachedProperty的类(例如DigitsOnlyBehavior)将上述答案转换为行为。设置附加属性后,您将注册在行为类中定义并实现的处理程序。
一个简短的例子:
public static class MyBehavior
{
public static readonly DependencyProperty AllowOnlyDigitsProperty = DependencyProperty.RegisterAttached(
"AllowOnlyDigits", typeof(bool), typeof(MyBehavior), new PropertyMetadata(default(bool), OnAllowOnlyDigitsChanged));
private static void OnAllowOnlyDigitsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBox = d as TextBox;
if (textBox == null) return;
textBox.PreviewTextInput += PreviewTextBoxInput;
}
public static void SetAllowOnlyDigits(DependencyObject element, bool value)
{
element.SetValue(AllowOnlyDigitsProperty, value);
}
private static void PreviewTextBoxInput(object sender, TextCompositionEventArgs e)
{
var textbox = sender as TextBox;
if (!char.IsDigit(e.Text, e.Text.Length - 1))
e.Handled = true;
}
public static bool GetAllowOnlyDigits(DependencyObject element)
{
return (bool) element.GetValue(AllowOnlyDigitsProperty);
}
}
正如您所看到的,PreviewTextBoxInput函数主要是前一篇文章所建议的内容。
您现在可以"附加"您的XAML中的行为是这样的:
<TextBox local:MyBehavior.AllowOnlyDigits="True" />
此解决方案尚未完全完成,因为它不支持更改属性(每次属性更改时它都会附加处理程序,因此它假定您只通过XAML设置一次)。但是如果你不想在运行时改变这种行为,那你就没事了。