How to use a ContextMenu with a TextBox MenuItem?
Posted on 2010-03-29
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;