c# - How do I get a DataGrid Cell to stop the user entering an incorrect value? -
i have followed article how to: implement validation datagrid control though not prevent user leaving cell, wish leave cell focussed. consider cell bound integer value, trying enter alpha character not allow focus removed cell.
my grid follows:
<datagrid headersvisibility="column" autogeneratecolumns="false" canuseraddrows="false" canuserdeleterows="false" canuserresizerows="false" itemssource="{binding selectedlines}"> <datagrid.rowvalidationrules> <exceptionvalidationrule /> </datagrid.rowvalidationrules> <datagrid.columns> <datagridtextcolumn isreadonly="true" header="name" binding="{binding name}"/> <datagridtextcolumn isreadonly="false" header="qty" binding="{binding quantity, validatesonexceptions=true}"/> </datagrid.columns> </datagrid>
my datasource observablecollection
of object following:
public class myentry : inotifypropertychanged /*, ieditableobject*/ { public myentry(string name) { this.name = name; this.quantity = 1; } public string name { get; private set; } private int quantity; public int quantity { { return quantity; } set { if (quantity != value) { if (value < 1) throw new argumentexception("quantity may not less 1."); if (value > 100) throw new argumentexception("quantity may not more 100."); quantity = value; onpropertychanged("quantity"); } } } #region inotifypropertychanged members public event propertychangedeventhandler propertychanged; protected void onpropertychanged(string propertyname) { if (propertychanged != null) propertychanged(this, new propertychangedeventargs(propertyname)); } #endregion #region ieditableobject members private int backupquantity; private bool inedit; public void beginedit() { if (inedit) return; inedit = true; backupquantity = this.quantity; } public void canceledit() { if (!inedit) return; inedit = false; this.quantity = backupquantity; } public void endedit() { if (!inedit) return; inedit = false; backupquantity = 0; } #endregion }
no matter do, grid not show there error, i.e. there no red box around cell, further want stop user leaving focus. if enter 'x' cell behaves correctly, though if enter -1, not commit value because grid not allow me try , edit row , pressing escape
on original cell reverts correctly.
i know if there property grid exposes in error, way can bind validation such accept button not being enabled.
in special case datagrid has no chance there wrong because underlying data not noticed wrong.
when bind vm property of type int , in ui set value xyz example - thing raise bindingexception, xyz never come down vm.
its common problem in mvvm , wpf. time use strings , idataerrorinfo interface in viewmodels , masked textboxen input in ui. benefit of can handle every input im vm idataerrorinterface. have little bit more work map string right type of model (e.g string in vm int in model).
if @ output window while debugging should see bindingexception.
i know not real answer...
Comments
Post a Comment