Reputation: 75
I'm trying to implement the standard "recent files" option under a file menu. The code below shows the list of options correctly, but when clicking a sub-menu that contains a fileName the binding to the command does not work.
<MenuItem Header="File">
<MenuItem Header="New File..." Command="{Binding NewFileCommand}" />
<MenuItem Header="Open File..." Command="{Binding OpenFileCommand}" />
<MenuItem Header="Recent Files"
ItemsSource="{Binding Path=RaptManager.RaptConfiguration.RecentFiles}"
Command="{Binding OpenFileCommand}">
<ItemsControl.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Header" Value="{Binding}"/>
<Setter Property="Command" Value="{Binding OpenFileCommand}"/>
</Style>
</ItemsControl.ItemContainerStyle>
</MenuItem>
</MenuItem>
Upvotes: 0
Views: 1199
Reputation: 3760
I don't know what type is the object you're using to represent a recent file. I'm assuming you're using string, although you might be using any other type as well.
You're receiving this error because the binding framework is looking for a property named OpenFileCommand on the type you're using to represent the recent file and not in the view model.
So the solution is to use an element binding in order to bind to the command in the view model referencing the DataContext of the view directly:
Put a name to the Menu control for instance:
<MenuItem x:Name="Menu" Header="File">
</Menu>
Now you can do an element binding to the DataContext of the Menu:
<MenuItem Header="Recent Files"
ItemsSource="{Binding Path=RaptManager.RaptConfiguration.RecentFiles}"
Command="{Binding OpenFileCommand}">
<ItemsControl.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Header" Value="{Binding}" />
<Setter Property="Command" Value="{Binding ElementName=Menu, Path=DataContext.OpenFileCommand}" />
</Style>
</ItemsControl.ItemContainerStyle>
</MenuItem>
Note in the style Setter for the Command property in the ItemsControls' ItemContainerStyle that we're referencing the Property OpenFileCommand of the DataContext property of the Menu element. That's an element binding. If you want to know more about it, check this link.
This way, you should be able to get the view command properly bound to the Command property in your view model.
Hope this helps!
Upvotes: 1