I am working on the WPF application. In my application there are different forms which save the data. I want to validation the data on button click or while lost focus from control. I want WPF validations work likes ASP.Net validation.
I do not know the form validate after page load. It should only validate when user lost focus from control or while user click on button.
I have done lot of R&D on google. But I did found any proper setup by setup solution.
Please help me out.
Asked
Active
Viewed 1,282 times
0

jellysaini
- 158
- 5
- 15
1 Answers
-1
In this example I show you two text box with validation...
XAML Coding......
<TextBlock Text="Throw Exception in Property" Grid.Column="1" Grid.Row="0" VerticalAlignment="Center" FontSize="22" Foreground="Chocolate" />
<TextBlock Text="Name " Grid.Column="0" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="15" Foreground="DarkGreen" />
<TextBlock Text="Age" Grid.Column="0" Grid.Row="2" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="15" Foreground="DarkGreen" />
<TextBox Name="txtName" Grid.Row="1" Grid.Column="2" HorizontalAlignment="Left" Width="170" Height="30" Background="Azure" Text="{Binding Path=pName,Mode=TwoWay,ValidatesOnExceptions=True}"/>
<TextBox Name="txtAge" Grid.Row="2" Grid.Column="2" HorizontalAlignment="Left" Width="170" Height="30" Background="Azure" Text="{Binding Path=pAge,Mode=TwoWay,ValidatesOnExceptions=True}"/>
<Button Name="btnSubmit" Content="Submit" Grid.Row="4" Height="30" Click="btnSubmit_Click"/>
C# Coding
private void Page_Loaded(object sender, RoutedEventArgs e)
{
Student s = new Student();
this.DataContext = s;
}
public class Student : INotifyPropertyChanged
{
string name;
int age;
public string pName
{
get
{
return name;
}
set
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("Name field must be enterd.");
}
name = value;
OnPropertyChanged("pName");
}
}
public int pAge
{
get
{
return age;
}
set
{
if(!Regex.IsMatch(value.ToString(),"[0-9]"))
{
throw new ArgumentException("Age field must be in number.");
}
if(value < 18 || value > 100)
{
throw new ArgumentException("Age field must be 18-100.");
}
age = value;
OnPropertyChanged("pAge");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string data)
{
if (PropertyChanged != null)
{
PropertyChanged(this,new PropertyChangedEventArgs(data));
}
}
}

Bhushankumar Lilapara
- 780
- 1
- 13
- 26