【问题标题】:Prevent copying content from specific datagrid text column防止从特定数据网格文本列复制内容
【发布时间】:2019-10-11 08:30:07
【问题描述】:

我想阻止用户从我定义为 DataGridTextColumn 的 WPF DataGrid 中的列中复制内容

设置ClipboardContentBinding="{x:Null}" 无效,对我来说这是防止任何内容被复制的最明显方法。

<DataGrid.Columns>
    <DataGridTextColumn Header=Field"
                        Binding="{Binding Name}"
                        ClipboardContentBinding="{x:Null}" />
</DataGrid.Columns>

我希望输出为 string.empty(甚至不包含在 ClipboardContents 中),因为 ClipboardContentBinding 设置为 null。相反,它实际上是在复制名称。

编辑 01: 我试过:ClipboardContentBinding="{x:Static Binding.DoNothing}" 但这没有用。我得到一个例外: System.ArgumentException: Object of type 'MS.Internal.NamedObject' cannot be converted to type 'System.Windows.Data.BindingBase'.

的作用 是设置绑定到将失败的路径。例如:

ClipBoardContentBinding="{Binding InvalidPath}" 其中InvalidPath 不存在于被绑定的对象上...有没有比依赖魔术字符串路径更好的方法?

【问题讨论】:

  • 这可能会有所帮助:stackoverflow.com/questions/12780961/…
  • @Sach,我使用的不是 Windows 窗体,而是 WPF。
  • 这不是确切的答案,它指向正确的方向。看看那个接受的答案,抑制按键可能仍然对你有用。
  • 这会起作用,但它会阻止编辑列。您可以将列的IsReadOnly 设置为true。如果您需要能够进行编辑,那么我认为您需要使用该列的CellStyle 属性提供DataTemplate。然后使用Sach的建议禁用TextBox上的一些操作

标签: c# wpf xaml datagrid


【解决方案1】:

还有另一种方法可以通过在CommandManager.PreviewExecuted 事件中限制复制命令来禁用复制。

XAML

<DataGridTextColumn Header=Field" Binding="{Binding Name}" >
    <DataGridTextColumn.EditingElementStyle>
        <Style TargetType="{x:Type TextBox}">
            <EventSetter Event="CommandManager.PreviewExecuted" Handler="textBox_PreviewExecuted"/>
        </Style>
    </DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>

代码背后

private void textBox_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
    if (e.Command == ApplicationCommands.Copy)
    {
        e.Handled = true;
    }
}

【讨论】:

    【解决方案2】:

    您可以通过以下方式完成您想要的。

    包括命名空间 xmlns:sys="clr-namespace:System;assembly=mscorlib"

    定义一个空字符串资源:

        <UserControl.Resources>
            <x:Static x:Key="stringEmpty" Member="sys:String.Empty" />
        </UserControl.Resources>

    将资源引用为 Source 而不是 Path:

    &lt;DataGridTextColumn Binding="{Binding Key}" ClipboardContentBinding="{Binding Source={StaticResource ResourceKey=stringEmpty}}" /&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-04
      相关资源
      最近更新 更多