Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
720
Access xamgrid instance in xamgrid contextmenu
posted

Hi

I have a xamgrid within which I have a xamgrid.contextmenu. I also have the below command class.

Command class

public class CopyToClipboardCommand : Freezable, ICommand
{
public static readonly DependencyProperty DataGridProperty =
DependencyProperty.Register("DataGrid", typeof (XamGrid),
typeof (CopyToClipboardCommand)
);

public XamGrid DataGrid
{
get { return (XamGrid)GetValue(DataGridProperty); }
set { SetValue(DataGridProperty, value); }
}

protected virtual void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}

#region ICommand

public bool CanExecute(object parameter)
{
return true;
}

public event EventHandler CanExecuteChanged;

public void Execute(object parameter)
{
DataGrid.CopyToClipboard();
}

#endregion

protected override Freezable CreateInstanceCore()
{
return new CopyToClipboardCommand();
}

}

I bind the above class to one of the menu item as shown below

// Bindings not shown for clarity

<ig:XamGrid x:Name="grid">

<ig:XamGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy">
<MenuItem.Command>
<commands:CopyToClipboardCommand
DataGrid="{Binding ElementName=grid}"/>
</MenuItem.Command>
</MenuItem>
</ContextMenu>
</ig:XamGrid.ContextMenu>

</ig:XamGrid>

The grid instance is always passed as null to the Execute and the CanExecute methods. I guess somehow the context menu is not able to access the xamgrid instance even though I use binding elementName=grid. Can you let me know what is going wrong here that I'm not able to access the xamgrid instance inside my command class?

Thanks

Chev

  • 34830
    Verified Answer
    Offline posted

    Hello Ranjith,

    The reason for this issue is that the ContextMenu is not in the same visual tree as the XamGrid.

    As a solution, you can use a binding similar to the following:

    <ContextMenu DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}">

                        <MenuItem Header="Copy">

                            <MenuItem.Command>

                                <commands:CopyToClipboardCommand DataGrid="{Binding}"/>

                            </MenuItem.Command>

                        </MenuItem>

                    </ContextMenu>

    Please reach out to me if you have any other questions or concerns.

    Sincerely,
    Andrew
    Developer Support I
    Infragistics.Inc
    www.infragistics.com/support