views:

17

answers:

1

I have defined a datagrid like this ::

 <cc:PEDataGrid AutoGenerateColumns="False"
               ItemsSource="{Binding Rows}"
               Width="Auto"                
               PreviewMouseRightButtonDown="PEGrid_PreviewMouseRightButtonDown"
               Loaded="CommonPEGrid_Loaded">             
      <wpfkit:DataGrid.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Cut" />
            <MenuItem Header="Copy"/>
            <MenuItem Header="Paste"/>              
        </ContextMenu>
    </wpfkit:DataGrid.ContextMenu>
</cc:PEDataGrid>

This shows contextMenu on every cell when right click is done.
I want to disable context menu for all the cells except headers and also on header for some condition. (I dont want to use DataGridHeaderStyle because of some other problems which I dont want to explain here.)

I have defined a handler for PreviewMouseRightButtonDown on the datagrid and in the handler I am trying to do something like this::

    private void PEGrid_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        DependencyObject depObj = (DependencyObject)e.OriginalSource;

        while ((depObj != null) && !(depObj is DataGridColumnHeader))
        {
            depObj = VisualTreeHelper.GetParent(depObj);
        }

        if (depObj == null)
        {
            return;
        }

        if (depObj is DataGridColumnHeader)
        {
            //some condition here which says whether contextmenu is required on this header

            (depObj as DataGridColumnHeader).ContextMenu = null;
            //the above line is not working!!!!
        }
        else
        {
             (depObj as DataGridCell).ContextMenu = null;
              //the above line not working!!!!
         }
    }

I want to know where am I going wrong!! Please help me regarding this. Also guide me to do in a better way if I am achieving my requirement in a wrong way :)

A: 

Hey I Solved it :: My modified code is as follows:::

private void PEGrid_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    DependencyObject depObj = (DependencyObject)e.OriginalSource;

    while ((depObj != null) && !(depObj is DataGridColumnHeader))
    {
        depObj = VisualTreeHelper.GetParent(depObj);
    }

    if (depObj == null)
    {
        return;
    }

    if (depObj is DataGridColumnHeader)
    {
          dg.ContextMenu.Visibility = Visibility.Visible;  //works
    }
    else
    {
          dg.ContextMenu.Visibility = Visibility.Collapsed; //works
     }
}
Guru Charan