Greetings All,
I am getting some weird behavior from WPF when i create an event to programatically open a context menu. once I select a text and right click the highlight of the selection disappears once the context menu opens up.
Here is a sample of the problem:
Xaml:
<Window x:Class="WpfApplication19.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="287" Width="419">
<Grid>
<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>
<Label Height="30" Margin="12,0,136,91" Name="label2" VerticalAlignment="Bottom">TextBox Open ContextMenu by programmatically</Label>
<TextBox Height="38" Margin="0,0,6,81" x:Name="myText1" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="135" />
</Grid>
</Window>
And the Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication19
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
ContextMenu con = new ContextMenu();
public Window1()
{
InitializeComponent();
MenuItem menuItem1 = new MenuItem();
menuItem1.Header = "Menu1";
MenuItem menuItem2 = new MenuItem();
menuItem2.Header = "Menu2";
con.Items.Add(menuItem1);
con.Items.Add(menuItem2);
this.myText.ContextMenu = con;
this.myText1.PreviewMouseDown += new MouseButtonEventHandler(myText1_PreviewMouseDown);
}
void myText1_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
base.OnPreviewMouseDown(e);
if (e.RightButton == MouseButtonState.Pressed)
{
con.Placement = System.Windows.Controls.Primitives.PlacementMode.MousePoint;
con.IsOpen = true;
IInputElement focusedElement = FocusManager.GetFocusedElement(this);
}
}
}
}
Thank you in advance!
Note: I found out that adding con.focusable = false tends to work with the solution. but can anybody explain why is that?