c# - How to successfully implement WPF textbox validation? -
i'm trying implement should simple textbox validation wpf application, i'm having problems.
i used guide: http://www.codeproject.com/tips/690130/simple-validation-in-wpf
my textbox in mainwindow.xaml:
<textbox x:name="textbox1" horizontalalignment="left" height="23" margin="93,111,0,0" textwrapping="wrap" verticalalignment="top" width="120" style="{staticresource textboxinerror}" validation.errortemplate="{staticresource validationerrortemplate}"> <textbox.text> <binding path="name" updatesourcetrigger="propertychanged"> <binding.validationrules> <local:namevalidator/> </binding.validationrules> </binding> </textbox.text> </textbox>
my namevalidator class in mainwindow.xaml.cs:
public class namevalidator : validationrule { public override validationresult validate(object value, system.globalization.cultureinfo cultureinfo) { if (value == null) return new validationresult(false, "value cannot empty."); else { if (value.tostring().length > 3) return new validationresult(false, "name cannot more 3 characters long."); } return validationresult.validresult; } }
my static resources in app.xaml:
<controltemplate x:key="validationerrortemplate"> <dockpanel> <textblock foreground="red" dockpanel.dock="top">!</textblock> <adornedelementplaceholder x:name="erroradorner"></adornedelementplaceholder> </dockpanel> </controltemplate> <style x:key="textboxinerror" targettype="{x:type textbox}"> <style.triggers> <trigger property="validation.haserror" value="true"> <setter property="tooltip" value="{binding relativesource={x:static relativesource.self}, path=(validation.errors)[0].errorcontent}"/> </trigger> </style.triggers> </style>
i can run application without errors, validation never triggered.
using posted, works fine me, produces red "!" above textbox. however, did remember set datacontext, ie.
public mainwindow() { initializecomponent(); this.datacontext = this; }
without this, won't work.
Comments
Post a Comment