0

Possible Duplicate:
How do I get a TextBox to only accept numeric input in WPF?

I am currently working on a WPF application where I would like to have a TextBox that can only have numeric entries in it (including the point and minus sign).

I know how to do this in Windows Forms, but the WPF events are very different to me.

Community
  • 1
  • 1
oscar.fimbres
  • 1,145
  • 1
  • 13
  • 24

1 Answers1

0

Just add a handler for the keydown event and set e.handled=true for key you don't want to allow. The sample is on the page and handle alt-p and alt-n but same principle. You are going to need to modify this code as it was not designed to cancel a key stroke but it does show how to handle the keydown event.

    <Window x:Class="Gabe2a.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
    DataContext="{Binding Source={x:Static Application.Current}}"
    Title="Gabriel Main" Height="600" Width="800" KeyDown="Window_KeyDown">

    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        // Debug.WriteLine("Main Window Window_KeyDown " + e.Key.ToString());
        e.Handled = false;
        if (e.KeyboardDevice.Modifiers == ModifierKeys.Alt) //  && e.KeyboardDevice.IsKeyDown(Key.RightAlt))
        {
            if (e.Key == Key.System && e.SystemKey == Key.N)
            {
                e.Handled = true;
                App.StaticGabeLib.Search.NextDoc();
            }
            else if (e.Key == Key.System && e.SystemKey == Key.P)
            {
                e.Handled = true;
                App.StaticGabeLib.Search.PriorDoc();
            }
        }
        base.OnKeyDown(e);
    }

Sample for attaching the KeyDown to a TextBox

            <TextBox KeyDown="TBKeydown" />
paparazzo
  • 44,497
  • 23
  • 105
  • 176
  • Specific example how to impliment the above code for the TextBox (you don't want to do it for the whole window, if you can avoid it) http://social.msdn.microsoft.com/forums/en-US/wpf/thread/d2d816c2-898f-4b4e-9756-96b6c5eb44e7 – EtherDragon Aug 09 '11 at 23:38
  • You just attached the event to the TextBox. Event syntax is the same for any type of control. With WPF there is an event bubbling that is very helpful that you may want to read up on. – paparazzo Aug 11 '11 at 12:44