简体   繁体   中英

How to Pass Current DataGridCell Information from WPF Style

I'm having a Style of TargetType=DataGridCell, it contains the ContextMenu. I need to Pass the DataGridCell Information to that Command via CommandParameter.

<Style TargetType="{x:Type DataGridCell}" x:Key="DataGridCellStyle">
    <Setter Property="ContextMenu">
        <Setter.Value>
            <ContextMenu>
                <MenuItem Header="Copy" Command="{Binding CopyToClipBoardCommand, Mode=OneWay}" CommandParameter={}>
                    <MenuItem.DataContext>
                        <cust:CopytoContext/>
                    </MenuItem.DataContext>
                </MenuItem>
            </ContextMenu>
        </Setter.Value>
    </Setter>
</Style>

xmlns:cust="clr-namespace:MyProject.Util"

The Class Source Code

public class CopytoContext
{
    #region Commands

    public ICommand CopyToClipBoardCommand
    {
        get
        {
            return new DelegatingCommand((object param) =>
            {
                new Action(() =>
                {
                     /// Logic to Copy the Content to Clipboard
                }).Invoke();
            });
        }
    }

    #endregion
}

How to I Pass the Current DataGridCell Information to that Command. Kindly assit me...

If you prefer to avoid using names for your controls, well you can use a RelativeSource binding:

<Style TargetType="{x:Type DataGridCell}">
    <Setter Property="ContextMenu">
        <Setter.Value>
            <ContextMenu>
                <MenuItem Header="Copy" Command="{Binding CopyToClipBoardCommand, Mode=OneWay}"
                            CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}, Path=PlacementTarget}">
                    <MenuItem.DataContext>
                        <cust:CopytoContext />
                    </MenuItem.DataContext>
                </MenuItem>
            </ContextMenu>
        </Setter.Value>
    </Setter>
</Style>

The PlacementTarget property of the ContextMenu returns the control which the ContextMenu is attached to (the cell in this case). Then in your command you can use this code:

DataGridCell dataGridCell = param as DataGridCell;
if (dataGridCell != null)
{
    TextBlock textBlock = dataGridCell.Content as TextBlock;
    if (textBlock != null)
    {
        Clipboard.SetText(textBlock.Text);
    }
}

I hope it can help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM