一个WPF只能输入数字的行为。

没啥好说的,直接上代码:

 public class NumberInputBehaviour : Behavior<TextBox>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            InputMethod.SetIsInputMethodEnabled(AssociatedObject, false);
            AssociatedObject.PreviewTextInput += AssociatedObject_PreviewTextInput;
            AssociatedObject.TextChanged += AssociatedObject_TextChanged;
            AssociatedObject.LostFocus += AssociatedObject_LostFocus;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.PreviewTextInput -= AssociatedObject_PreviewTextInput;
            AssociatedObject.TextChanged -= AssociatedObject_TextChanged;
            AssociatedObject.LostFocus -= AssociatedObject_LostFocus;
        }

        private void AssociatedObject_LostFocus(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(AssociatedObject.Text))
            {
                if (!string.IsNullOrEmpty(NullText))
                {
                    AssociatedObject.Text = NullText;
                }
            }
        }

        private void AssociatedObject_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (Convert.ToInt32(AssociatedObject.Text) == 0)
            {
                AssociatedObject.Text = "500";
                AssociatedObject.SelectionStart = AssociatedObject.Text.Length;
            }
        }

        private void AssociatedObject_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            Regex re = new Regex("[^0-9]+");
            e.Handled = re.IsMatch(e.Text);

         
        }



        public String NullText
        {
            get { return (String)GetValue(NullTextProperty); }
            set { SetValue(NullTextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for NullText.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty NullTextProperty =
            DependencyProperty.Register("NullText", typeof(String), typeof(NumberInputBehaviour), new PropertyMetadata(""));


    }

xaml 使用方法 :

 <TextBox>
    <i:Interaction.Behaviors>
     <local:NumberInputBehaviour NullText="请输入"></local:NumberInputBehaviour>
    </i:Interaction.Behaviors>
 </TextBox>

OK....