问题
Thought of asking because never done this before on a TextBlock. I Am not able to copy the content of the DataGridTemplateColumn where it has a TextBlock in that and i have assigned a context menu to that.
The copied content is blank.
When I tried in MS word is Blank Cell.
My Template Column and ContextMenu are as below.
I Tried using TextBox But it work when the textbox is enabled and in-spite of grid column is readonly. It allows editing and when we disable it won't copy the text.
<DataGridTemplateColumn Header="Details" Width="*" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding details}" TextWrapping="Wrap">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy" Command="Copy"></MenuItem>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
回答1:
Why the copied content is empty string is that TextBlock does not support Copy, Cut and Past Commands like TextBox. So If using TextBlock, you'll need to support these commands manually, but you can use TextBox to support the copy command, which could act as TextBlock. Please check the following.
<TextBox Background="Transparent" BorderThickness="0" Text="{Binding details}" IsReadOnly="True" TextWrapping="Wrap">
<TextBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy" Command="Copy"></MenuItem>
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
[updated]
First of all, the code below can be executed correctly?
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Background="Transparent" BorderThickness="0" Text="test" IsReadOnly="True" TextWrapping="Wrap">
<TextBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy" Command="Copy"></MenuItem>
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
</Grid>
</Window>
回答2:
In my particular case, I fixed the issue by:
- Removing
IsReadOnly
from the row. - Instead of using
Command=Copy
, I usedCommand="{Binding CopyToClipboard}"
with a binding of the command to the ViewModel behind the row.
来源:https://stackoverflow.com/questions/7909390/copy-command-on-contextmenu-over-textblock-inside-datagridtemplatecolumn