1

I have the following XAML used to populate a sub-MenuItem listing with RecentDocuments:

<MenuItem Header="_Recent Studies" 
          ItemsSource="{Binding RecentFiles}"
          AlternationCount="{Binding Path=Items.Count, 
                                     Mode=OneWay, 
                                     RelativeSource={RelativeSource Self}}" 
          ItemContainerStyle="{StaticResource RecentMenuItem}"/>

Where in the ViewModel I have the following RecentFiles property

private ObservableCollection<RecentFile> recentFiles = new ObservableCollection<RecentFile>();
public ObservableCollection<RecentFile> RecentFiles
{
    get { return this.recentFiles; }
    set
    {
        if (this.recentFiles == value)
            return;
        this.recentFiles = value;
        OnPropertyChanged("RecentFiles");
    }
}       

Now this works fine and displays my recent menu items like so:

MenuItems

My question is; how can I bind to the click event on my recent files MenuItems? I am amble to use AttachedCommands but I don't see how this can be achieved.

thanks for your time.

MoonKnight
  • 23,214
  • 40
  • 145
  • 277

1 Answers1

2

If you are using MVVM pattern, you do not need Click event at all.

You should use MenuItem.Command property in order to communicate with your ViewModel.

HOW?

As I can see, you are using the ItemContainerStyle. You can add the following line to that style:

<Style x:Key="RecentMenuItem" TargetType="MenuItem">
    ...
    <Setter Property="Command" Value="{Binding Path=SelectCommand}" />
    ...
</Style>

And in your RecentFile:

 public ICommand SelectCommand { get; private set; }

You can initialize the command inside the constructor of RecentFile class.

stukselbax
  • 5,855
  • 3
  • 32
  • 54
  • Yes, but how? That _is_ the question. The reason I am having trouble is that the items are populated at run-time... – MoonKnight Oct 14 '13 at 16:37
  • Ah of course. Stupidness. However, to get the binding to work from the style you will need: ``. Thanks for your time. – MoonKnight Oct 14 '13 at 18:38