将ListView的项目复制到WPF中的剪贴板C#

时间:2010-03-11 15:29:37

标签: c# wpf listview clipboard

如何将WPF的ListView中的选定项目与db字段绑定到剪贴板?

谢谢你 克里斯蒂安

3 个答案:

答案 0 :(得分:6)

由于您需要显示的内容而不是类的属性上的数据,因此您需要直接从控件中获取数据。

        var sb = new StringBuilder();
        foreach(var item in this.listview1.SelectedItems)
        {
            var lvi = this.listview1.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem;
            var cell = this.GetVisualChild<ContentPresenter>(lvi);
            var txt = cell.ContentTemplate.FindName("txtCodCli", cell) as TextBlock;
            sb.Append(txt.Text);
            //TODO: grab the other column's templated controls here & append text
        }
        System.Windows.Clipboard.SetData(DataFormats.Text, sb.ToString());

这假设您的XAML中有

<TextBlock x:Name="txtCodCli" TextAlignment="Left" Text="{Binding Path=VFT_CLI_CODICE}" />

“GetVisualChild T在哪里

    public T GetVisualChild<T>(Visual parent) where T : Visual
    {
        T child = default(T);
        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++)
        {
            Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
            child = v as T;
            if (child == null)
            {
                child = GetVisualChild<T>(v);
            }
            if (child != null)
            {
                break;
            }
        }
        return child;
    }

答案 1 :(得分:4)

我认为您必须监视SelectionChanged事件,然后以特定文本格式格式化项目,然后使用Clipboard.SetText方法将项目设置到剪贴板中。

http://msdn.microsoft.com/en-us/library/system.windows.clipboard.aspx

private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
        foreach (var item in e.AddedItems.OfType<ListViewItem>())
        {
                Clipboard.SetText(item.ToString());
        }
}

答案 2 :(得分:1)

我这样解决了。我添加了 Ctrl + C 事件监听器,然后添加了要复制到剪贴板的逻辑

XAML

<Window 
    ....
        Loaded="Window_Loaded"
        ...>

用代码

private void WindowKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.C && Keyboard.Modifiers == ModifierKeys.Control)
            {
                var sb = new StringBuilder();
                var selectedItems = LVLog.SelectedItems;

                foreach(var item in selectedItems)
                {
                    sb.Append($"{item.ToString()}\n");
                }

                Clipboard.SetDataObject(sb.ToString());
            }
        }