Paste Event in a WPF TextBox

前端 未结 7 771
情深已故
情深已故 2020-11-30 20:10

I have created a custom control inheriting TextBox. This custom control is a numeric TextBox, only supporting numbers.

I am using OnP

7条回答
  •  北海茫月
    2020-11-30 21:01

    The below code worked for me. I hope, it will help someone.

    Use the below code if you are using Xceed RichTextBox control.

      
    
     private void CommandExecuted_PreviewExecuted(object sender, RoutedEventArgs e)
        {
            Xceed.Wpf.Toolkit.RichTextBox richTextBox =  (Xceed.Wpf.Toolkit.RichTextBox)sender;
    
            string rtbtext = StringFromRichTextBox(richTextBox);
            if ((e as ExecutedRoutedEventArgs).Command == ApplicationCommands.Paste)
            {
                // verify that the textbox handled the paste command
                if (Clipboard.GetText() > 2500)//Get copied text from clipboard
                {
                    e.Handled = true;// prevent paste if length is more than 2500.
                    return;
                }
            }
        } 
    

    If you are using TextBlock, then use below code

    TextBlock textBlock = (TextBlock)sender;
    

    instead of this

    Xceed.Wpf.Toolkit.RichTextBox richTextBox =  (Xceed.Wpf.Toolkit.RichTextBox)sender;
    

    Rest all codes can remain the same as above for TextBlock as well.

提交回复
热议问题