Wednesday, 2 May 2012

WPF: Dynamic Menu

In one of projects I am working on, we have a requirement of showing ‘recent files’ used by the application. The files used by the application are XML files – no custom extension.

Our goal is:

 image

For this task we need the following things:
- a RecentFiles class:
    - should contain the list of recent files
    - should have methods to load/save the list to disk (persistence)
    - should have methods to add a recent file used or delete a non-existing file
- a MenuItem (with children) to show the list

Here is the RecentFiles class:

public partial class RecentFiles
    {
          private ObservableCollection<string> filesField;
          public ObservableCollection<string> Files
          {
              get
              {
                   return this.filesField;
              }
              set
              {
                  this.filesField = value;
          }

          //members for persistence – Load, Save
         //you can find the full class definition in attachments
}

In the Windows.cs, we have a view model WindowViewModel having a property named AppRecentFiles.

Code in WindowViewModel:
      public RecentFiles AppRecentFiles { get; set; }

Code in Windows.cs:
     this._mainWindowViewModel = new MainWindowViewModel();
      this.DataContext = this._mainWindowViewModel;

Now the XAML part:

<MenuItem x:Name="mnuRecentFiles" Header="_Recent Files" ItemsSource="{Binding AppRecentFiles.Files}">
    <MenuItem.Resources>
        <Style TargetType="MenuItem">
            <Setter Property="Command" Value="{Binding ElementName=mnuRecentFiles, Path=DataContext.RecentFileChosenCommand}" />
            <Setter Property="CommandParameter" Value="{Binding}" />
        </Style>
    </MenuItem.Resources>
</MenuItem>


And you are done with the basic infrastructure.

Now all we have to do is:
- add an item to the AppRecentFiles.Files list whenever we load a new file (from the Load option in menu). Tip: add the new item at top of list so that it shows as first item on the menu.
- remove file from list if the user selects a file from 'recent files’ is not found, perhaps after a confirmation message box
- load the recent files by using RecentFiles.LoadFromFile() method – usually done during Window load or app start
- and save (persist) the list by calling RecentFiles.SaveToFile() on App close or window close

No comments:

Post a Comment

Note: only a member of this blog may post a comment.