c#


Required field Validation in WPF text box


I need a simple way to validate of text boxes (Required Field). It should check all mandatory field existence , when user press button.
I have tried this code :
<Window.Resources>
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="25" Text="*" DockPanel.Dock="Right" />
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
</Window.Resources>
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Height="26" Margin="62,213,0,0" VerticalAlignment="Top" Width="121" Click="Button_Click_1"/>
<TextBox x:Name="txtEmail1" Text="" Height="61" Margin="116,10,194,0" Validation.ErrorTemplate="{StaticResource validationTemplate}"/>
</Grid>
please anyone suggest a way to make validation in Text boxes in WPF.
Thank you
You should bind the Text property of the TextBox to a property of a view model and implement the IDataErrorInfo interface in the view model class.
Please refer to the following sample code.
Code:
public partial class Window3 : Window
{
Window3ViewModel viewModel = new Window3ViewModel();
public Window3()
{
InitializeComponent();
DataContext = viewModel;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
viewModel.Validate();
}
}
public class Window3ViewModel : INotifyDataErrorInfo
{
private readonly Dictionary<string, string> _validationErrors = new Dictionary<string, string>();
public void Validate()
{
bool isValid = !string.IsNullOrEmpty(_text);
bool contains = _validationErrors.ContainsKey(nameof(Text));
if (!isValid && !contains)
_validationErrors.Add(nameof(Text), "Mandatory field!");
else if (isValid && contains)
_validationErrors.Remove(nameof(Text));
if (ErrorsChanged != null)
ErrorsChanged(this, new DataErrorsChangedEventArgs(nameof(Text)));
}
public bool HasErrors => _validationErrors.Count > 0;
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public IEnumerable GetErrors(string propertyName)
{
string message;
if (_validationErrors.TryGetValue(propertyName, out message))
return new List<string> { message };
return null;
}
private string _text;
public string Text
{
get { return _text; }
set
{
_text = value;
}
}
}
XAML:
<Window x:Class="WpfApp2.Window3"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="Window3" Height="300" Width="300">
<Window.Resources>
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="25" Text="*" DockPanel.Dock="Right" />
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
</Window.Resources>
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Height="26" Margin="62,213,0,0" VerticalAlignment="Top" Width="121" Click="Button_Click_1"/>
<TextBox x:Name="txtEmail1" Text="{Binding Text}" Height="61" Margin="116,10,194,0" Validation.ErrorTemplate="{StaticResource validationTemplate}"/>
</Grid>
</Window>
And please refer to the following blog post for more information about how data validation in WPF works.
Data validation in WPF: https://blog.magnusmontin.net/2013/08/26/data-validation-in-wpf/

Related Links

Using Data-binding expressions in HyperLinkField
Select statement using list of key value pairs in where clause
Ajax method call failed after website was deployed
Property 'VersionID' is part of the object's key information and cannot be modified
Adding item from Listview to a database
Really small font in AutoCAD table
Update DLL thats in use with Prism during runtime
Entity Framework Error - The relationship could not be changed because one or more of the foreign-key properties is non-nullable
WPF TreeView Selected Item and showing User Controls
How to rename files in unknown directory using c#
How to add a Video Encoder to windows to be recognized by DirectShow
Is there any web service which we can use to get all the us cities latitude longitude values? [closed]
Lists inside list in C#
Defining Label.Text leads to a NullReferenceException
Stop visual studio 2013 from repositioning braces on new line?
c# Abstract Generic Class inheriting from Abstract Generic Class

Categories

HOME
oop
grizzly
leaflet
aix
highmaps
datetimepicker
symfony-sonata
perl6
angularjs-directive
sequence
virtualhost
pyodbc
box-api
digital
jcodemodel
http-status-codes
sha1
appsettings
css-float
web-parts
jquery-easyui
loader
printf
hl7-fhir
lotusscript
quality-center
chartist.js
inspec
spock
ipython-parallel
openoffice-impress
jsonapi-resources
headphones
campaign-monitor
azure-storage-files
mapquest
nsdateformatter
ngrok
java-5
php-mongodb
web-technologies
taiga
smooth-streaming
result
stream-socket-client
history
standard-error
critical-section
qt3d
blitz3d
ownership
firebase-polymer
mate-desktop
particle-system
key-value-store
bytearray
aws-kms
hana-sql-script
fadein
clear
dynamics-nav
newlib
magnet-uri
maven-antrun-plugin
updating
openhab
azure-mobile-app
android-networking
gcc-warning
sony-xperia
shunting-yard
fedena
report-builder2.0
diffmerge
parsefloat
redmine-plugins
episerver-7
opencobol
mdp
autofilter
thucydides
wpa
friendly-url
azure-scheduler
pudb
cloudmade
biztalk-deployment
nsregularexpression
quit
motordriver
flatten
jmesa
scriptmanager
cgaffinetransform
jqzoom
clgeocoder
mcpd
mscorlib
cherokee
flexbuilder
backlight
netduino
newspeak
coderush-xpress
rpxnow
script-tag
disk-based
cstring
office-2003
hotfix

Resources

Encrypt Message