WPF: Add a command to auto-generated by binding menu items
Again, found the solution by myself. I tried to put the command in wrong way like below, and it doesn't work:
<MenuItem Header="_Recent files" ItemsSource="{Binding RecentFiles, Converter={StaticResource RecentFilesToListOfStringsConverter}, Mode=OneWay}" > <MenuItem.ItemContainerStyle> <Style TargetType="{x:Type MenuItem}"> <Setter Property="Command" Value="{Binding ImportRecentItemCommand}" /> </Style> </MenuItem.ItemContainerStyle> </MenuItem>
Here is the right approach. Still don't understand how it works, have to learn WPF deeply!
<MenuItem Header="_Recent files" ItemsSource="{Binding RecentFiles, Converter={StaticResource RecentFilesToListOfStringsConverter}, Mode=OneWay}" > <MenuItem.ItemContainerStyle> <Style TargetType="{x:Type MenuItem}"> <Setter Property="Command" Value="{Binding DataContext.ImportRecentItemCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type MenuItem}, AncestorLevel=1}}" /> </Style> </MenuItem.ItemContainerStyle> </MenuItem>
EDIT: The final version
XAML:
<MenuItem Header="_Recent files" ItemsSource="{Binding RecentFiles, Converter={StaticResource RecentFilesToListOfStringsConverter}, Mode=OneWay}" > <MenuItem.ItemContainerStyle> <Style TargetType="{x:Type MenuItem}"> <Setter Property="Command" Value="{Binding DataContext.ImportRecentItemCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type MenuItem}, AncestorLevel=1}}" /> <Setter Property="CommandParameter" Value="{Binding}" /> </Style> </MenuItem.ItemContainerStyle> </MenuItem>
ViewModel: MVVM Light Toolkit is used, RelayCommand goes from there:
private ICommand _importRecentItemCommand; public ICommand ImportRecentItemCommand { get { return _importRecentItemCommand ?? (_importRecentItemCommand = new RelayCommand<object>(ImportRecentItemCommandExecuted)); } } private void ImportRecentItemCommandExecuted(object parameter) { MessageBox.Show(parameter.ToString()); }
Enjoy