[WPF TextBox] When the context menu is displayed, the selected character string of TextBox is canceled.

Akira OMOSHITA 21 Reputation points

I have a question about WPF TextBox.
Right-clicking with a character selected in the TextBox opens a standard context menu.
However, if you right-click outside the selected string, the string will be deselected.
I don't want to clear the selected string when I open the context menu like the address bar in Explorer.
(Right-click on the selected string to open the context menu as desired.)

The same result was achieved by opening my own context menu within the TextBox.
Is there a good solution?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,369 questions
{count} votes

Accepted answer
  1. Castorix31 71,626 Reputation points

    You can handle OnContextMenuOpening.
    Something like :

    public partial class MyTextBox : TextBox
        protected override void OnContextMenuOpening(ContextMenuEventArgs e)
            int nSelStart = this.SelectionStart;
            int nSelLength = this.SelectionLength;
            this.Select(nSelStart, nSelLength);

1 additional answer

Sort by: Most helpful
  1. Hui Liu-MSFT 17,381 Reputation points Microsoft Vendor

    You could try to add con.focusable = false; so that the string is still selected when you right-click to display the context menu.
    The code of xaml:

            <TextBox x:Name="myText" Height="38" Margin="0,72,6,0" VerticalAlignment="Top" HorizontalAlignment="Right" Width="135"></TextBox>  
            <Label Height="30" Margin="12,80,164,0" Name="label1" VerticalAlignment="Top">Textbox with contextMenu property set</Label>  

    The code of xaml.cs:

    public partial class MainWindow : Window  
        ContextMenu con = new ContextMenu();  
        public MainWindow()  
          MenuItem menuItem1 = new MenuItem();  
          menuItem1.Header = "Menu1";  
          MenuItem menuItem2 = new MenuItem();  
          menuItem2.Header = "Menu2";  
          con.Focusable = false;  
          this.myText.ContextMenu = con;  

    The picture of result:

    If the response is helpful, please click "Accept Answer" and upvote it.
     Note: Please follow the steps in our [documentation][3] to enable e-mail notifications if you want to receive the related email notification for this thread. 

    [3]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html