In this post we will discuss how to use the ContextMenu using MVVM pattern. You can find the beginner level of article about how to use ContextMenu on the web. But here I will show you how to use it using MVVM pattern. This is also first time that I am using the ContextMenu control of the Silverlight. So if there is any error or if you feel that I have miss something related to the ContextMenu then please let me now about it.
For this example I have used the Text Box control when you right click on the text box it will display the ContextMenu in the Text Box control. As you can see in the Image 1 when user right click inside the Text Box control Context Menu open with the cut, copy and paste option in it. Here you can also see that I have also place TextBlock control with text "Message will be displayed here" which will show you the menu item click concatenated with the Time.
Image 1 |
In List 1 you can see the xaml to add the Context Menu in the Text Box control. Here you see that I have used Silverlight toolkit ContextMenuService which will handle the event and positioning of the ContextMenu and I have placed it inside the Text Box control. Here you can see for every menu item I have set the Header like Cut Text, Copy Text and Paste Text which you will see as label as see in the Image 1 and also you can see that I have also use the icon property of the menu item to show the icon for every menu item.
List 1
If you don't want to show icon for any menu item then you can remove the icon property. After setting the header and the Icon property of the menu item next is the binding of the command to the Command property of the view model. Here I have used only one command for all the menu item which is the MenuClickCommand and in the CommandProperty I have passed some text which will identify the sender of the click event as in the code behind we can identify it by converting the send of the event but as in case of command we can't have UI information so I have used the CommandParameter for every menu item so that I can Identify send of the event.
Image 2 |
When user click any of the menu item text is update to show which menu item is click and when it is clicked (mean the time stamp) which you can see in the Image 2 the message are highlighted. You can perform what action you required when any of the menu item is click. I have simply show text in the main page to show the menu item click you can perform operation like cut , copy paste or even save, update , edit and cancel operation depending on your requirement.You can download the source code from here.
All and any comments / bugs / suggestions are welcomed!
All and any comments / bugs / suggestions are welcomed!
No comments:
Post a Comment