簡體   English   中英

將副本右鍵單擊上下文菜單添加到XAML中的數據網格列

[英]Adding copy right click Context menu to data grid column in xaml

 <DataGridTextColumn Header="S.No" Binding="{Binding SerialNumberId}"
                                            IsReadOnly="True">

                            <DataGridTextColumn.CellStyle>
                                <Style TargetType="DataGridCell" >
                                    <Setter Property="ContextMenu">
                                        <Setter.Value>
                                            <ContextMenu>
                                                <MenuItem Command="Copy"></MenuItem>
                                        </ContextMenu>
                                    </Setter.Value>
                                    </Setter>
                               </Style>
                            </DataGridTextColumn.CellStyle>  
                        </DataGridTextColumn>

我想在數據網格的此特定列“ S.No”的上下文菜單中添加復制選項。 但是整個行的內容將被復制,而不僅僅是網格中的一個單元。 如何僅復制應用了上下文的一個單元格而不復制整個行?

為您的命令使用CommandParamter,如下所示:

CommandParameter="{Binding RelativeSource={RelativeSource Self}}"

在代碼中更改Command參數,就可以使用它了。

您可以在DataGrid上添加CommandBinding以綁定到函數:

<DataGrid x:Name="dataGrid1" AutoGenerateColumns="False">
    <DataGrid.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Copy" Executed="DatagridExecuted" />
    </DataGrid.CommandBindings>
    <DataGrid.Columns>
      ...
    </DataGrid.Columns>
</DataGrid>

在函數中,您可以找到事件的來源,

獲得對應於一行的DataContext,

並從DataContext中獲取可以放入剪貼板的確切屬性

private void DatagridExecuted(object sender, ExecutedRoutedEventArgs e)
{
    DataGridCell cell = e.OriginalSource as DataGridCell;
    if (cell != null)
    {
        Product product = cell.DataContext as Product;
        if (product != null)
        {
            Clipboard.SetText(product.SerialNumberId);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM