Reputation: 21280
I am trying to bind MenuItem
dynamically.
I have public List<string> LastOpenedFiles { get; set; }
is my data source.
My command that I try to run is public void DoLogFileWork(string e)
<MenuItem Header="_Recent..."
ItemsSource="{Binding LastOpenedFiles}">
<MenuItem.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Header"
Value="What should be here"></Setter>
<Setter Property="Command"
Value="What should be here" />
<Setter Property="CommandParameter"
Value="What should be here" />
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
I want on each entry from LastOpenedFiles
is I click on it to go to DoLogFileWork
function with the entry value that I clicked on.
Thanks for assistance.
Upvotes: 1
Views: 179
Reputation: 6113
<Setter Property="Header" Value="What should be here"></Setter>
Nothing, you've already set this above to _Recent...
<Setter Property="Command" Value="What should be here"/>
<Setter Property="CommandParameter" Value="What should be here"/>
Are you using a MVVM approach? If so, you'll need an ICommand
exposed on the ViewModel that the Window/Control is bound to, take a look at the RelayCommand
mentioned in this article (or is native in VS2012 I believe).
This is the sort of thing you'd setup in your VM:
private RelayCommand _DoLogFileWorkCommand;
public RelayCommand DoLogFileWorkCommand {
get {
if (null == _DoLogFileWorkCommand) {
_DoLogFileWorkCommand = new RelayCommand(
(param) => true,
(param) => { MessageBox.Show(param.ToString()); }
);
}
return _DoLogFileWorkCommand;
}
}
Then in your Xaml:
<Setter Property="Command" Value="{Binding ElementName=wnLastOpenedFiles, Path=DataContext.DoLogFileWorkCommand}" />
<Setter Property="CommandParameter" Value="{Binding}"/>
So here, you're binding the Command
of the MenuItem
to be the DoLogFileWorkCommand
declared above, and CommandParameter
is being bound to the string in the List that the MenuItem is bound to.
Upvotes: 1