c# - Bound WPF TextBox is not updating value when the bound property enforces some business rules -
i using .net 4.0. have simple code lets user type in number between 1 , 99,999 (inclusive). have logic in property setter prevents latest value being applied if not adhere business rules (e.g., not number or number large).
public class mainviewmodel : inotifypropertychanged { #region fields private string _text = string.empty; #endregion // fields #region properties public string text { { return _text; } set { if (_text == value) return; if (isvalidrange(value)) { _text = value; } onpropertychanged("text"); } } #endregion // properties #region private methods private bool isvalidrange(string value) { // empty string considered valid. if (string.isnullorwhitespace(value)) return true; // try convert unsigned integer, since negative bill numbers not allowed, // nor decimal places. uint num; if (!uint.tryparse(value, out num)) return false; // value parse, know non-negative integer. now, // need make sure in range of 1 - 99999, inclusive. return num >= 1 && num <= 99999; } #endregion // private methods #region inotifypropertychanged implementation public event propertychangedeventhandler propertychanged; [notifypropertychangedinvocator] protected virtual void onpropertychanged(string propertyname) { propertychangedeventhandler handler = propertychanged; if (handler != null) handler(this, new propertychangedeventargs(propertyname)); } #endregion // inotifypropertychanged implementation }
the problem running when value not valid , ignore value, textbox bound property not update reflect change; rather, retains value typed in. here how have property bound:
<textbox grid.row="0" text="{binding path=text, updatesourcetrigger=propertychanged, mode=twoway}"/>
can tell me i'm doing wrong?
i have read lot of questions seemed similar this, none of answers worked me. weird thing when don't validate based on numbers, change text typed in upper case, works fine. seems not work when try not set property new value.
this seems bug textbox
in .net 3.5-4.0. first tried in 4.5 , code worked written, when converted project 4.0, reproduce issue. after doing searching, found:
wpf textbox refuses update while binded view model property, details workaround references:
textbox getting out of sync viewmodel property.
of course if it's possible use .net 4.5 i'd suggest that, of course it's not easy that.
Comments
Post a Comment