开发者

Copy a ListView’s Items to the Clipboard in WPF C#

开发者 https://www.devze.com 2022-12-22 10:55 出处:网络
how can I copy t开发者_JAVA技巧he selected items in a WPF\'s ListView with binding to db fields to the Clipboard?

how can I copy t开发者_JAVA技巧he selected items in a WPF's ListView with binding to db fields to the Clipboard?

thank you Cristian


I would think you would have to monitor for SelectionChanged events and then format the items in a particular text format and then utilize the Clipboard.SetText method to set the items into the clipboard.

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());
        }
}


Since you want what is being displayed as opposed to the data on your class's properties you will need to grab the data from the controls directly.

        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());

This assumes that in your XAML you have

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

"Where GetVisualChild T is

    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;
    }


I solved it this way. I have added Ctrl + C event listener and then added logic to copy to clipboard

XAML

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

in code

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());
            }
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号