Nemanja11
Nemanja11

Reputation: 21

How to get validation ( xaml and C# ) textbox for int value?

Need to validate if the datatype of user input is int, but I have no idea how to do it!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Projekat.Validation
{
    public partial class ValidationExample : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }

        private int _test1;

        public int Test1
        {
            get
            {
                return _test1;
            }
            set
            {
                if (value != _test1)
                {
                    _test1 = value;
                    OnPropertyChanged("Test1");
                }
            }
        }

        public ValidationExample()
        {
            //InitializeComponent();
            //this.DataContext = this;
        }

    }
}

AND

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace Projekat.Validation
{
    public class StringToIntValidationRule:ValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            try
            {
                var s = value as string;
                int r;
                if (int.TryParse(s, out r))
                {
                    return new ValidationResult(true, null);
                }
                return new ValidationResult(false, "Please enter a valid int value.");
            }
            catch
            {
                return new ValidationResult(false, "Unknown error occured.");
            }
        }
    }
}

AND part of xaml for textbox

<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="145,40,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="120">
    <TextBox.Text>
        <Binding Path="Test1" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <val:StringToIntValidationRule ValidationStep="RawProposedValue"/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>

                <AdornedElementPlaceholder Grid.Column="0" Grid.Row="0" x:Name="textBox"/>
                <TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding [0].ErrorContent}" Foreground="Red"/>
            </Grid>
        </ControlTemplate>
    </Validation.ErrorTemplate>
</TextBox>

Upvotes: 2

Views: 1147

Answers (1)

lena
lena

Reputation: 1191

Your code is OK, the only issue I found is that the property Test1 may never be set because of incorrect DataContext in the binding. It seems that Test1 belongs to Window, so I would give this window a name in xaml:

<Window x:Name="win".../>

And after that all you need is add DataContext to a textbox:

<TextBox DataContext="{Binding ElementName=win}" .../>

Upvotes: 1

Related Questions