Link to home
Start Free TrialLog in
Avatar of FlorianStruck
FlorianStruckFlag for Germany

asked on

How to use a ContextMenu with a TextBox MenuItem?

Below you'll find my basic WPF / C# code to create and show a Context Menu. I currently got two problems I want to address here.

1.) The TextBox appears in the ContextMenu. But whenever I click it (to enter a text) the context menu disappears (like when clicking normal context menu entries. But it should just close when my Cursor is in the Box and I hit the 'Enter' button or when I leave the TextBox it should behave like a normal context menu (closed when clicking on main window...)

2.) Whenever the text of the TextBox is changing I would like to update Item2 - to a text like the text of the TextBox + additional text. E.g. if you enter "Hello" in the TextBox, Item2 changes from "Entry2" to "Hello World". This should happen on every key you enter so at first it would be "H World" after entering the second key "He World" and so on...

System.Windows.Controls.ContextMenu Menu = new System.Windows.Controls.ContextMenu ( );
System.Windows.Controls.MenuItem      Item1      = new System.Windows.Controls.MenuItem ( );      
System.Windows.Controls.MenuItem      Item2      = new System.Windows.Controls.MenuItem ( );      
System.Windows.Controls.TextBox      Box      = new System.Windows.Controls.TextBox ( );
                                          
Box.AcceptsReturn                  = true;
Box.MaxLength                  = 25;      
Box.Text                              = "Text to edit";                              
                                                                                    
Item1.Header                        = Box;
Item2.Header                        = "Entry 2";
Menu.Items.Add                  ( Item1 );
Menu.Items.Add                  ( Item2 );
Menu.IsOpen                        = true;
ASKER CERTIFIED SOLUTION
Avatar of CuteBug
CuteBug
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of FlorianStruck

ASKER

I would like to stick to a ContextMenu if possible.

I just disovered when I set Menu.IsCheckable = true that I at least can insert a new text (when my mouse is exactly over the TextBox), but of course a 'Checked' Arrow appears left of my TextBox.
I did is a popup now, thanks!