c# - Enable WPF button based on checkbox list selection in MVVM -


i have checkbox list items , submit button. submit button need disabled. button needs enabled selection of single checkbox selection or multiple selections. add below code in xaml , backend code need have view model suing mvvm.

xaml..

<listbox grid.row="1" borderthickness="0" background="transparent" name="list" itemssource="{binding items}" margin="10 5 20 0" selectionmode="extended">                     <listbox.itemtemplate>                         <datatemplate>                             <stackpanel orientation="horizontal">                                 <checkbox name="check" ischecked="{binding ischecked, mode=twoway}" margin="5 5 0 10" verticalalignment="center" />                                 <contentpresenter content="{binding value}" margin="5 5 0 10"/>                             </stackpanel>                         </datatemplate>                     </listbox.itemtemplate>                 </listbox>  <button grid.row="2" click="button_click" horizontalalignment="right" height="25" width="60" margin="0,0,30,0" isenabled="{binding path=isbuttonenabled}">                    <textblock>submit</textblock> </button> 

so how view model implement using onpropertychanged().

you'll need register propertychanged events of each item in view model , aggregate results. example:

class viewmodel {     public viewmodel()     {         items = new observablecollection<item>();          propertychangedeventhandler propertychangedhandler = (o, e) =>         {             if (e.propertyname == nameof(item.ischecked))                 onpropertychanged(nameof(isbuttonenabled));         };          items.collectionchanged += (o, e) =>         {             if (e.olditems != null)                 foreach (var item in e.olditems.oftype<inotifypropertychanged>())                     item.propertychanged -= propertychangedhandler;             if (e.newitems != null)                 foreach (var item in e.newitems.oftype<inotifypropertychanged>())                     item.propertychanged += propertychangedhandler;         };     }      public observablecollection<item> items { get; }      public bool isbuttonenabled => items.any(i => i.ischecked); } 

another option consider using reactiveui.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -