Friday, March 06, 2009

How to create context menus and capture right click event in Silverlight


Context menus & right click event is something which is not out of the box supported in silverlight but I think they prove to be very crucial while developing LOB applications. So here is a workaround on how you can create them. Basically I am using HTML/Javascript to create and render menus on top of silverlight but it involves a few tweaks which are listed below.

First tweak is – How to display a HTML Menu on top of silverlight control.
For this we need to change 2 properties on the .aspx or .html page where the silverlight control is being hosted.

      <param name="background" value="transparent" />
  
<param name="windowless" value="true" />


Than capturing the right click event in HTML and displaying our menu.

<
script language="javascript">

  function click(e) {
     if (navigator.appName == 'Microsoft Internet Explorer' && event.button == 2) {

                var menu = document.getElementById('myMenu');
                menu.style.left = event.clientX + 'px';
                menu.style.top = event.clientY + 'px';
                menu.style.visibility = 'visible';
                return false;
            }
            return true;
  }
  document.onmousedown = click

</script>

'myMenu'
is a <div> I have created on the html page which contains a simple table as below:

<
div id="myMenu" style="position: absolute; visibility: hidden; width: 75px">

   <table width="100%" style="background: #000000" cellspacing="1" cellpadding="1">
    
<tr style="background: #FFFFFF">
         <td onclick="SomeFunctionWhichCallsSilverlight()" style="cursor: hand">
             
Edit
        
</td>
    
</tr>
     <tr style="background: #FFFFFF">
         <td onclick="SomeFunctionWhichCallsSilverlight()" style="cursor: hand"> 
              Save

        
</td>
    
</tr>
     <tr style="background: #FFFFFF">
         <td onclick="SomeFunctionWhichCallsSilverlight()" style="cursor: hand"> 
              ________

        
</td>
    
</tr>


     <tr style="background: #FFFFFF">
         <td onclick="SomeFunctionWhichCallsSilverlight()" style="cursor: hand"> 
              Exit

        
</td>
    
</tr>

   </table>


</
div>

The SomeFunctionWhichCallsSilverlight() function would be the interop function to call the relevant Silverlight function as described in my earlier blog.

Now the last thing is to disable the default ‘SilverlightConfiguration’ menu

<body oncontextmenu="return false">


You can download the sample code from here

No comments:

AddIn