I want to know if I could assign item click event to this context menu that it is placed in an .Xaml file of type ResourceDictionary
which one does not have code behind class, however i know that i can manually assign a .cs class to this .xaml.
But I dont want to assign a file class to it because I already have another .Xaml file with its own .cs file class in which i would want to register the itemClick event.
My code in the resourcedictionary file is:
<ContextMenu>
<MenuItem Header="Show SoundRecorder" Click="ItemClick"></MenuItem>
<Separator/>
<MenuItem Header="Start Recording Now"></MenuItem>
<MenuItem Header="Stop Recording"></MenuItem>
<Separator/>
<MenuItem Header="About"></MenuItem>
<MenuItem Header="Exit SoundRecorder"></MenuItem>
</ContextMenu>
How could i achieve this approach?
Create a command in a data context for the view with the context menu.
public ICommand ItemClickCommand{ get; set; }
Then, you can bind the MenuItem's Command property to the new command.
<ContextMenu>
<MenuItem Header="Show SoundRecorder" Command="{Binding ItemClickCommand}"></MenuItem>
<Separator/>
<MenuItem Header="Start Recording Now"></MenuItem>
<MenuItem Header="Stop Recording"></MenuItem>
<Separator/>
<MenuItem Header="About"></MenuItem>
<MenuItem Header="Exit SoundRecorder"></MenuItem>
</ContextMenu>
At runtime, if WPF finds the command in the data context it will bind the menu item to it. Otherwise, it will issue a warning in the Output console.
I will not go here on implementing the ICommand
interface. There are plenty of googlable implementations.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.