Sunday, September 27, 2009

Silverlight DataGrid with Row-Aware Context Menu

 In my last post I talked about adding context-menus to controls. DataGrid is a control that we use in most projects, and it will be nice to have this context menu be aware of the row on which the user clicked and act on the datacontext for that row. Here is a sample application that demonstrates such bahavior:



The code can be found here.

We are creating the context menu and handling right-clicks the same way as described in my earlier post. The main thing is to create a DataGrid which can tell you the row that is clicked. I found that if you inherit from DataGrid, you have access to the RowsPresenter.


   1:  protected const string PRESENTER_CHILD_NAME = "RowsPresenter";
   2:  protected DataGridRowsPresenter presenter;
   3:   
   4:  public override void OnApplyTemplate()
   5:  {
   6:     base.OnApplyTemplate();
   7:     presenter = (DataGridRowsPresenter)GetTemplateChild(PRESENTER_CHILD_NAME);
   8:  }

I took the row and set it as the "Tag" of the Menu Item. Now we have context.


   1:  public virtual List<ContextMenuItemInfo> GetContextMenuContent(System.Windows.Browser.HtmlEventArgs e)
   2:  {
   3:      Point curr = new Point(e.OffsetX, e.OffsetY);
   4:      for (var i = 0; i < presenter.Children.Count; i++)
   5:      {
   6:          var row = (DataGridRow)presenter.Children[i];
   7:          if (ContextMenuInterceptor.IsPointWithinBounds(curr, row))
   8:          {
   9:              foreach (ContextMenuItemInfo m in ContextMenuList)
  10:              {
  11:                  m.Tag = row;
  12:              }
  13:              return ContextMenuList;
  14:          }
  15:      }
  16:      return null;
  17:  }

5 comments:

  1. When I try to right click first i see "silverilght" popup and after when It dissapear than I see the context menu.
    I think if you can please remove the silverlight popup which is shown first.

    ReplyDelete
  2. I have seen that with the host + Firefox. When I test on my local machine, it looks ok. I think it is some weirdness with the script that is served by Silverlight Live site (which hosts this app). A friend confirmed that the right-click functionality works ok with Chrome, fwiw.

    ReplyDelete
  3. When I try to right click, i see only "silverilght" popup and nothing else. What could be the problem.

    ReplyDelete
  4. You might want to have a look at this project:
    http://sl4popupmenu.codeplex.com/

    ReplyDelete
  5. This solution was for SL3 (pre-SL4).

    ReplyDelete