c# - Context Menu commands to dynamically create UI controls using MVVM -


hopefully question isn't general, have started using wpf , i'm banging head against this.

i developing application uses dynamically created controls. can not figure out how make commands create , add more controls current window because commands work when created in viewmodel can not see view. can't keep in xaml because controls except few empty stack panels dynamic. feel i'm missing easy here though.

so here have binding

<menuitem header="labelmenuitem" command="{binding path=spawnlabel}"/> 

and here have command

 public icommand spawnlabel { { return new delegatecommand(onspawnlabel); } } 

delegate command works relay command defined here.

public class delegatecommand : icommand     {         private readonly action _command;         private readonly func<bool> _canexecute;         public event eventhandler canexecutechanged         {             add { commandmanager.requerysuggested += value; }          remove { commandmanager.requerysuggested -= value; }     }      public delegatecommand(action command, func<bool> canexecute = null)     {         if (command == null)             throw new argumentnullexception();         _canexecute = canexecute;         _command = command;     }      public void execute(object parameter)     {         _command();     }      public bool canexecute(object parameter)     {         return _canexecute == null || _canexecute();     }  } 

this works in view model can't figure out how on earth make work in view (or talk view without breaking mvvm principles) can change ui using current controls created in c#.

currently when bindingexpression path error makes sense can not figure out how bind command in view.

you indirectly communicate ui via events, if change property fire propertychanged, ui update binding, if change collection fire collectionchanged , new control added or old 1 removed.

the important interfaces inotifypropertychanged , inotifycollectionchanged, bind itemscontrol (via itemssource) observablecollection<t> in view-model , add collection in command (you may need use itemscontrol.itemtemplate specify view view-models, depending on mvvm framework use).


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -