Bind Items to MenuItem -> use Command
binding, c#, menu, menuitem, wpf
Solution
This should work for you
<MenuItem Header="From Database"
ItemsSource="{Binding YourItemSource}">
<MenuItem.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=MenuItem}, Path=DataContext.YourCommandName}"></Setter>
<Setter Property="CommandParameter" Value="{Binding}"></Setter>
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
Problem
I have a MenuItem, which has a collection of items in it. It looks like the File -> Open Menuitem. So: - File - Open - Open from DataBase - File 1 - File 2 - File 3 XAML Code: ``` <Menu> <MenuItem Header="File"> <MenuItem Header="Open"> <MenuItem Header="From Database" ItemsSource="{Binding OCFragebogen}"/> </MenuItem> </MenuItem> </Menu> ``` I want to call a Command, when a specific item has been clicked. Example: User clicks on File 1, a command should be called where the "File 1" is the Command Parameter. ViewModel contains the Items, which I want to display in the MenuItem "collection" ``` private ObservableCollection<string> _OCFragebogen; public ObservableCollection<string> OCFragebogen { get { if (_OCFragebogen == null) _OCFragebogen = new ObservableCollection<string>(); return _OCFragebogen; } set { _OCFragebogen = value; RaisePropertyChanged(() => OCFragebogen); } } ``` To make it clear: When the user clicks on an item (from the ItemsSource) in the MenuItem, a Command should be called where I want to do something with the clicked Item. Edit: Where do I have to use the command to call a method (RelayCommand) in my ViewModel? I want it to be used when an Item from the ItemsSource has been clicked + I want to pass the clicked item to the method.