c# - WPF/MVVM - Checking A MenuItem Based On String Match -


i'm attempting implement theme-selection menu in wpf/mvvm application. i've got selection working, can't seem figure out how set ischecked on appropriate menuitem pure databinding (aka without breaking mvvm pattern).

xaml:

<menuitem header="_theme">     <menuitem header="classic" command="{binding changethemecommand}" commandparameter="classic" />     <menuitem header="metro white" command="{binding changethemecommand}" commandparameter="metrowhite" /> </menuitem> 

viewmodel:

relaycommand _changethemecommand; public icommand changethemecommand {         {       return _changethemecommand ?? (_changethemecommand = new relaycommand(param =>        {           thememanager.currenttheme = param.tostring();       }));      } } 

the theming being handled actipro's wpf control suite (http://www.actiprosoftware.com); can see, current theme represented string only.

my problem lies in figuring out how bind ischecked in way mark menuitem active theme. way xaml structured, mean matching current theme name menuitem's commandparameter.

any tips/pointers appreciated.

your first problem hard-coding themes. better create class called theme:

public class theme : inotifypropertychanged {     public string name { get; set; } // implement propertychanged event on this.     public bool checked { get; set; } // implement propertychanged event on this. } 

in main view model, have observable collection of these, fill themes, i.e.:

observablecollection<theme> themes { get; private set; } 

in constructor, like:

themes.add(new theme() { name = "classic" }); themes.add(new theme() { name = "metrowhite" }); 

now context menu should like:

<menuitem header="_theme" itemssource="{binding themes}">     <menuitem.itemtemplate>         <datatemplate>             <menuitem header="{binding name}" ischecked="{binding checked}" ischeckable="true"/>         </datatemplate>     </menuitem.itemtemplate> </menuitem> 

now, gives set of themes, , when click on 1 it's checked property set. can assign command menuitems, preferably part of theme class (i.e. theme.set() seems reasonable oo design me). should pretty straightforward here on.

update

how enforce 1 theme selected @ once?

assuming have mainviewmodel, extend theme constructor take reference mainviewmodel. in settheme() command, iterate on other themes making sure not checked.

void settheme() {     foreach (theme theme in mainviewmodel.themes)     {         if (theme != this)         {             theme.checked = false;         }     }      // actual theme setting . } 

why should implement inotifypropertychanged?

because above doesn't work if dont. sure, implement checked, matter of practice recommend implementing public accessible properties form part of interface. way if use viewmodel different view later on wants edit these properties, work.


Comments