c# - How to skip wpf validation when the model is initialized? -
c# - How to skip wpf validation when the model is initialized? -
i'm trying create wpf error validation textbox. looks pretty simple after days , trying many methods i'm still trying figure out proper way this.
here code (this not real code, example):
the textbox<textbox text="{binding model.name , updatesourcetrigger=propertychanged, validatesonexceptions=true}" style="{staticresource nametextboxstyle}" />
the style <style x:uid="style_81" x:key="nametextboxstyle}" targettype="{x:type textbox}"> <style.triggers> <trigger property="validation.haserror" value="true"> <trigger.setters> <setter property="tooltip" value="{binding relativesource={relativesource self},path= (validation.errors)[0].errorcontent}"/> </trigger.setters> </trigger> </style.triggers> </style>
the class public class someclass { public bool isnamemandatory { get; set; } string name; public string name { { homecoming name; } set { if (isnamemandatory && string.isnullorempty(value)) { throw new exception("name can not empty."); } if (value.length > 12) { throw new exception("name can not longer 12 charectors"); } name = value; onpropertychanged("name"); } } }
the problem: error validation working when model "initialized" , set blank value "name" exception raised messagebox instead of reddish rectangle tooltip. don't want display exception in messagebox.
my needs: need validate error on lostfocus of textbox , on demand
here how wpf validation done using binding.validationrules property:
in view:
xmlns:tools="clr-namespace:someappnamespace.tools" <textbox style="{staticresource somestyle}"> <textbox.text> <binding path="someproperty" updatesourcetrigger="lostfocus" > <binding.validationrules> <tools:somevalidationrule /> </binding.validationrules> </binding> </textbox.text> </textbox>
validationrule class located in tools (or equivalent of) namespace:
public class somevalidationrule : validationrule { public override validationresult validate(object value, cultureinfo cultureinfo) { var usertext = value string; homecoming string.isnullorwhitespace(usertext) ? new validationresult(false, "value must provided.") : new validationresult(true, null); } }
so, simple validationrule
checks textbox on lostfocus
, if textbox left empty returns validation error message...
last piece of puzzle "somestyle" style textbox above must have validation.errortemplate
defined... this:
<style x:key="somestyle" targettype="{x:type textbox}"> <setter property="validation.errortemplate"> <setter.value> <controltemplate > <!-- error template here. typically border reddish background , textbox lite colored text... --> </controltemplate> </setter.value> </setter> </style>
c# wpf validation xaml mvvm
Comments
Post a Comment