开发者

WPF ListView - How to copy individual cells

开发者 https://www.devze.com 2023-03-02 05:33 出处:网络
I have code where I can take a look at the SelectedItem and then output ToString() to get the record into the clipboard.

I have code where I can take a look at the SelectedItem and then output ToString() to get the record into the clipboard.

How can I detect what cell the user is right clicking on in order to copy just that cell in the SelectedItem?

For example, if I have Borrower Information and the user right-clicks on last name, I would like to give the ability to just copy last name to clipboard.

Thank you!

UPDATE:

Here is the code that I used as suggested by Josh, it worked great:

  private void BorrowerInfoCopyClicked(object sender, RoutedEventArgs e)
        {
            BorrowerViewModel vm = this.DataContext as BorrowerViewModel;
            if (vm != null)
            {
                Clipboard.SetData(DataFormats.Text, vm.CurrentTextBlockText);
            }
        }

        private void AddressCopyClicked(object sender, RoutedEventArgs e)
        {
            BorrowerViewModel vm = this.DataContext as BorrowerViewModel;
            if (vm != null)
            {
                Clipboard.SetData(DataFormats.Text, vm.CurrentTextBlockText);
            }
        }

        private void lstViews_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            BorrowerViewModel vm = this.DataContext as BorrowerViewModel;
            if (vm != null)
            {
                if (e.OriginalSource is TextBlock)
                {
   开发者_如何学C                 TextBlock txtBlock = e.OriginalSource as TextBlock;
                    vm.CurrentTextBlockText = txtBlock.Text;
                }

} }


I've done this by handling the PreviewMouseRightButtonDown event on the ListView and checking if e.OriginalSource is a TextBlock. If so, copy the txtBlk.Text to the clipboard. This code could either be in the code-behind of the View that contains the ListView, or as a behavior you attach to the ListView. If you need to use a context menu to perform the Copy operation, have a TextBlock field that you use to store a reference to the TextBlock, and in your method that responds to a MenuItem's click (or Command execution) reference the TextBlock there instead.

0

精彩评论

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