1

Possible Duplicate:
Validation in textbox in WPF

I am currently using this code to create a numeric only textbox

Xaml

<TextBox Height="22" HorizontalAlignment="Left" Margin="192,118,0,0" Name="Unit_ID"  VerticalAlignment="Top" Width="173" PreviewTextInput="UnitID_PreviewTextInput" TextInput="Unit_ID_TextInput" TextChanged="Unit_ID_TextChanged" /> 

and the C# codebehind

 private void UnitID_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            foreach (char c in e.Text)
                if (!Char.IsDigit(c))
                {
                    e.Handled = true;
                    break;
                }

is is possible to do this by using XAML EXCLUSIVELY?i am trying to minimize my .cs file

Community
  • 1
  • 1
deception1
  • 1,707
  • 5
  • 23
  • 27
  • 1
    I think you are looking for validations. google for "Validation in wpf" http://stackoverflow.com/questions/1346707/validation-in-textbox-in-wpf – JSJ Apr 05 '12 at 08:18
  • http://stackoverflow.com/questions/1268552/how-do-i-get-a-textbox-to-only-accept-numeric-input-in-wpf could have some helpful hints. – weeyoung Apr 05 '12 at 08:41

2 Answers2

3

If you bind the value of the TextBox's Text attribute to an int, you'll get a sort of validation, in as much as you won't be able to set the value of MyInt to anything other than an int (and the TextBox border will go red if you try).

In the XAML:

<TextBox Text="{Binding MyInt}"/>

In the presenter:

public class MyPresenter : INotifyPropertyChanged
{
    public int MyInt { get; set; }
    // ...
}

and set the DataContext of the XAML to an instance of MyPresenter.

Scroog1
  • 3,539
  • 21
  • 26
0

Just like you can't use pure HTML to get this done, you can't use XAML exclusively (to my knowledge). I get the whole "less is more" philosophy, but in this case you'll need at least SOME code, e.g. Regex, to validate the input.

Wim Ombelets
  • 5,097
  • 3
  • 39
  • 55