附加属性
public class TextBoxHelper
{
//IsNumericOnly 只能输入数字
public static bool GetIsNumericOnly(DependencyObject obj)
{
return (bool)obj.GetValue(IsNumericOnlyProperty);
}
public static void SetIsNumericOnly(DependencyObject obj, bool value)
{
obj.SetValue(IsNumericOnlyProperty, value);
}
public static readonly DependencyProperty IsNumericOnlyProperty =
DependencyProperty.RegisterAttached("IsNumericOnly", typeof(bool), typeof(TextBoxHelper), new PropertyMetadata(false, OnIsNumericOnlyChanged));
private static void OnIsNumericOnlyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBox = d as TextBox;
if (textBox != null)
{
if ((bool)e.NewValue)
{
DataObject.AddPastingHandler(textBox, TextBox_Pasting);
textBox.PreviewTextInput += TextBox_PreviewTextInput;
textBox.PreviewKeyDown += TextBox_PreviewKeyDown;
}
else
{
DataObject.RemovePastingHandler(textBox, TextBox_Pasting);
textBox.PreviewTextInput -= TextBox_PreviewTextInput;
textBox.PreviewKeyDown -= TextBox_PreviewKeyDown;
}
}
}
private static void TextBox_Pasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(string)))
{
var pastedText = e.DataObject.GetData(typeof(string)) as string;
if (!IsTextAllowed(pastedText))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
private static void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsTextAllowed(e.Text);
}
private static void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
{
e.Handled = true;
}
}
private static bool IsTextAllowed(string text)
{
return int.TryParse(text, out _);
}
}
Xaml
<TextBox Ex:TextBoxHelper.IsNumericOnly="True" InputMethod.IsInputMethodEnabled="False"></TextBox>