title: MVVM Dynamic Menu UI from binding with ViewModel
body: <p>I am working with a team on LoB application. We would like to have a dynamic <code>Menu</code> control, which creates the menu based on the logged in user profile. In previous development scenarios (namely ASP.NET) we use to iterate through data which describes collection and generate <code>MenuItem</code> dynamically. In MVVM how would I do this? Can I separate XAML view from ViewModel which describes menu elements?</p>
  
  <p><strong>Solution:</strong></p>
  
  <p>With inputs from commentators I were able to bind <code>Menu</code> dynamically with the data from ViewModel. This <a href="http://uicraftsman.com/blog/2008/11/26/building-a-databound-wpf-menu-using-a-hierarchicaldatatemplate/" rel="nofollow noreferrer">article</a> was of great help too.</p>
  
  <p>XAML:</p>
  
  <pre><code>&lt;HierarchicalDataTemplate DataType="{x:Type self:Menu}" ItemsSource="{Binding Path=Children, UpdateSourceTrigger=PropertyChanged}"&gt;
      &lt;ContentPresenter Content="{Binding Path=MenuText}" RecognizesAccessKey="True"/&gt;
  &lt;/HierarchicalDataTemplate&gt;
  
  [...]
  
  &lt;Menu Height="21" Margin="0" Name="mainMenu" VerticalAlignment="Top" HorizontalAlignment="Stretch" 
        ItemsSource="{Binding Path=MenuItems, UpdateSourceTrigger=PropertyChanged}" ItemContainerStyle="{StaticResource TopMenuItems}"&gt;
      &lt;Menu.Background&gt;
          &lt;ImageBrush ImageSource="/Wpf.Modules;component/Images/MenuBg.jpg" /&gt;
      &lt;/Menu.Background&gt;
  &lt;/Menu&gt;
  </code></pre>
  
  <p><code>Menu</code> data class:</p>
  
  <pre><code>public class Menu : ViewModelBase
  {
      public Menu()
      {
          IsEnabled = true;
          Children = new List&lt;Menu&gt;();
      }
  
      #region [ Menu Properties ]
  
      private bool _isEnabled;
      private string _menuText;
      private ICommand _command;
      private IList&lt;Menu&gt; _children;
  
      public string MenuText
      {
          get { return _menuText; }
          set
          {
              _menuText = value;
              base.OnPropertyChanged("MenuText");
          }
      }
  
      public bool IsEnabled
      {
          get { return _isEnabled; }
          set
          {
              _isEnabled = value;
              base.OnPropertyChanged("IsEnabled");
          }
      }
  
      public ICommand Command
      {
          get { return _command; }
          set
          {
              _command = value;
              base.OnPropertyChanged("Command");
          }
      }
  
      public IList&lt;Menu&gt; Children
      {
          get { return _children; }
          set
          {
              _children = value;
          }
      }
  
      #endregion
  }
  </code></pre>