从DataGrid单元格复制文本

7

我希望能够从DataGrid单元格复制文本。

  1. First possible solution could be setting SelectionUnit to Cell but that's not an option for me since I need to select FullRow
  2. Second possible approach was to have DataGridTemplateColumn with readonly TextBox in it. But there is an issue with styles. My previous question: DatagridCell style overriden by TextBox style. I need really bright color for text in row, but really dark in selected row.
  3. Third is to set IsReadOnly="False" on DataGrid and provide EditingElementStylefor DataGridTextColumn

    <Style x:Key="EditingStyle" TargetType="{x:Type TextBox}">
    <Setter Property="IsReadOnly" Value="True"/>
    </Style>
    ...  
    <DataGridTextColumn ... EditingElementStyle="{DynamicResource EditingStyle}"/>
    

    But here comes a really terrible bug WPF Datagrid Text Column allows one character text enter when the internal text box is set to read only.

你知道有没有其他解决方案或变通方法吗?谢谢。

编辑

我注意到来自扩展WPF工具包DataGrid没有这个bug,但它似乎有不同的结构,我无法应用我的DataGrid样式。

我发现,将只读的TextBox作为DataGridColumn的EditingElementStyle会带来进一步的问题。当使用单向绑定时,就不能将单元格设置为编辑状态。让用户覆盖DataGrid中显示的某些实体的ID是不可接受的。因此,它必须以某种方式是只读的,或至少是单向绑定

目前我完全没有解决这个问题的方法。还有其他方法可以让用户在选择和突出显示行的同时从单元格复制吗?我有没有忽略其他解决方案?谢谢您的阅读。


你的行是一个对象吗? - WiiMaxx
@WiiMaxx,DataGrid 的 ItemsSource 绑定到例如 ObservableCollection<Foo>,并且列基于 Foo 的属性。在 Column1 中是 Foo.Property1 等等。 - Kapitán Mlíko
也许这可以帮助您 http://msdn.microsoft.com/de-de/library/system.windows.uielement.inputbindings.aspx - WiiMaxx
1个回答

2
你可以采取一些不太正当的手段来获取当前单元格。在你的XAML中加入以下内容即可:
<DataGrid GotFocus="DataGrid_GotFocus" KeyDown="DataGrid_KeyDown">

并在代码后台中

private void DataGrid_GotFocus(object sender, RoutedEventArgs e)
{
    if(e.OriginalSource is DataGridCell)
        _currentCell = (DataGridCell) e.OriginalSource;
}

private void DataGrid_KeyDown(object sender, KeyEventArgs e)
{
    if(e.Key == Key.C && (e.SystemKey == Key.LeftCtrl || e.SystemKey == Key.RightCtrl))
    {
         //Transform content here, like
         Clipboard.SetText(_currentCell.Content);
    }
}

这应该就可以了,因为 GotFocus 在数据网格本身中的每次选择更改时都会被执行。


它对我不起作用。因为我目前没有代码后台,而且我现在也不会破坏它。另外,我的单元格无法聚焦,但还是谢谢你。 - Kapitán Mlíko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接