c# - Reset combobox selected item on set using MVVM -
i using combobox in wpf application , following mvvm. there list of strings want show in combobox.
xaml:
<combobox itemssource="{binding itemscollection}" selecteditem="{binding selecteditem}" />
view model:
public collection<string> itemscollection; // suppose has 10 values. private string _selecteditem; public string selecteditem { { return _selecteditem; } set { _selecteditem = value; trigger notify of property changed. } }
now code working absolutely fine. able select view , can changes in viewmodel , if change selecteditem viewmodel can see in view.
now here trying achieve. when change selected item view need put check value good/bad (or anything) set selected item else not set it. view model changes this.
public string selecteditem { { return _selecteditem; } set { if (somecondition(value)) _selecteditem = value; // update selected item. else _selecteditem = _selecteditem; // not update selected item. trigger notify of property changed. } }
now when execute code , somecondition(value) returns false, selecteditem returns old string value, in view selected item in combobox the value selected. lets assume have collection of 10 strings showing in combobox. values except second , fourth element (somecondition returns false 2nd , 4th value). want if select 2nd or 4th element selecteditem not change. code not doing properly. if select 2nd element view still displays 2nd element selected. know there wrong in code. it?
this interesting question. first agree other guys not recommended approach handle invalid selection. @blindmeis suggests, idataerrorinfo
1 of way solve it.
back question itself. solution satisfying @faisal hafeez wants is:
public string selecteditem { { return _selecteditem; } set { var olditem=_selecteditem; _selecteditem=value; onpropertychanged("selecteditem") if (!somecondition(value)) //if not satisfy condition, set item old item dispatcher.currentdispatcher.begininvoke(new action(() => selecteditem = olditem), dispatcherpriority.applicationidle); } }
dispatcher
elegant way handle ui synchronization during ui sync. example in case, want reset selection during selection binding.
a question here why have update selection anyway @ first. that's because selecteditem
, selectedvalue
separately assigned , display on combobox
not depend on selecteditem
(maybe selectedvalue
, not sure here). , interesting point if selectedvalue changes, selecteditem
must change selecteditem
not update selectedvalue
when changes. therefore, can choose bind selectedvalue
not have assign first.
Comments
Post a Comment