Hello,

I am trying to have a numeric box in WPF toolbox, I have the following code which is giving me the control in the tool box, but I am unable make it accept only the numeric input.

protected override void OnKeyDown(KeyEventArgs e)
{
      short val;
      if (!Int16.TryParse(e.key.ToString(), out val))
      {
        e.Handled = true;
      }    
}

The problem I am facing is:

1 - When I press the numeric key 1 the value taken is D1 where it is treated as a character and displayed in Textbox
2- The Xaml designer is not coming up

 Window x:Class="TEST.MainWindow"
        xmlns=""
        xmlns:x=""
        Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:TEST">
    <Grid>
  <my:NumericTextBox Height="23" HorizontalAlignment="Left" Margin="183,128,0,0" x:Name="TextBox1" VerticalAlignment="Top" Width="75" />
    </Grid>
    </Window>

The error is

Error 1 Undefined CLR namespace. The 'clr-namespace' URI refers to a namespace 'TEST' that is not included in the assembly.
Error 2 The type 'my:NumericTextBox' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.

However I am still able to run the app

I want to have a custom control for textbox accepting only numerics.Please suggest....

Regards

Dani AI

Generated

Short version: stop using KeyDown for character validation and build the control project so the XAML designer can resolve your type.

Key points and a ready pattern you can drop into a reusable control:

  • KeyDown gives you a Key enum (D1, NumPad1, etc.), not the actual typed character. Use PreviewTextInput (TextCompositionEventArgs.Text) to see the real character, and also handle paste/drag-and-drop.
  • Make the control class public, ensure its file Build Action is Compile, build the project, and if the control lives in another assembly add a project reference and use xmlns:my="clr-namespace:TEST;assembly=YourAssemblyName". The designer needs the compiled type to resolve it (that’s why the app might run but the designer complains).

Example NumericTextBox (basic, culture-aware decimal and paste handling):

using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

public class NumericTextBox : TextBox
{
    readonly string _dec = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;

    public NumericTextBox()
    {
        DataObject.AddPastingHandler(this, OnPaste);
    }

    protected override void OnPreviewTextInput(TextCompositionEventArgs e)
    {
        e.Handled = !IsAllowed(e.Text);
        base.OnPreviewTextInput(e);
    }

    bool IsAllowed(string text)
    {
        foreach (char c in text)
            if (!char.IsDigit(c) && c.ToString() != _dec && c != '-') return false;

        if (Text.Contains(_dec) && text.Contains(_dec)) return false; // prevent second decimal
        return true;
    }

    void OnPaste(object sender, DataObjectPastingEventArgs e)
    {
        if (e.DataObject.GetDataPresent(DataFormats.Text))
        {
            var txt = (string)e.DataObject.GetData(DataFormats.Text) ?? "";
            if (!IsAllowed(txt)) e.CancelCommand();
        }
        else e.CancelCommand();
    }
}

Troubleshooting / best practice: wrap any runtime-only startup in design-time checks (DesignerProperties.GetIsInDesignMode) so the designer won’t fail. ’s suggestion to validate on change works, but encapsulating the logic in a derived control (or an attached behavior) avoids repeating validation code across the app. Checklist: use PreviewTextInput + paste handling, make the class public, build, add reference if needed, and guard heavy constructor code for design-time.

Recommended Answers

All 5 Replies

I want to have a custom control for textbox accepting only numerics.Please suggest....

Then why dont you try it on change event? Use a variable and Just check for every new character and remove it if its not numeric. if its numeric copy the value to your variable and if its not numeric then
textbox.text = yourVariable;

And if you are using blend, then I will suggest you to use Visual Studio to debug and even writing the code because its really hard and time consuming to figure out the error in Blend.

Thank you for the response...But the point is I do not want to have the validation everytime I use the textbox, I would need a numeric box across the application and hence trying to have a custom component...

Are u using Blend?

No I am not using Blend for this...I am doing it in VS

Have you referenced your user control? If not then go to projects > add reference
Then browse your control library and everything will work fine. When I removed the reference from my project I got same errors, So I think you forgot to add reference.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.