mvvm - Input validation on Windows store app -
mvvm - Input validation on Windows store app -
in windows store app using mvvm have textbox 2 way binding should allow numeric values. proper procedure using mvvm ignore when non numeric key pressed?
the value beingness changed of inotifypropertychanged triggers when textbox loses focus. want instant validation properties. can't find proper simple illustration of this.
why not create attached property contain behavior? this:
class="lang-cs prettyprint-override">public class textboxhelper { public static bool getrestricttonumerical(dependencyobject obj) { homecoming (bool)obj.getvalue(restricttonumericalproperty); } public static void setrestricttonumerical(dependencyobject obj, bool value) { obj.setvalue(restricttonumericalproperty, value); } public static readonly dependencyproperty restricttonumericalproperty = dependencyproperty.registerattached("restricttonumerical", typeof(bool), typeof(textboxhelper), new propertymetadata(false, onrestricttonumericalchanged)); private static void onrestricttonumericalchanged(dependencyobject d, dependencypropertychangedeventargs e) { var tb = d textbox; if (tb == null) return; if ((bool)e.newvalue) tb.keydown += tb_keydown; else tb.keydown -= tb_keydown; } static void tb_keydown(object sender, windows.ui.xaml.input.keyroutedeventargs e) { e.handled = e.key < virtualkey.number0 || e.key > virtualkey.number9; } }
you'd utilize in xaml this:
<page x:class="app4.mainpage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:app4" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:ignorable="d"> <grid background="{themeresource applicationpagebackgroundthemebrush}"> <textbox verticalalignment="center" local:textboxhelper.restricttonumerical="true" inputscope="number" /> </grid> </page>
this, in opinion, clean mvvm approach input validations might required do. it's overkill simple question, it's more sophisticated validations.
validation mvvm windows-store-apps
Comments
Post a Comment