Reputation: 459
I have a ComboBox control inside Context menu for some Label Control that I have added in Code behind in wpf application. There are many Labels on the page that have Contextmenu. Basically it is like this LABEL contains ContextMenu and ContextMenu conntains Combobox. On Combobox's SelectionChanged event I want to know which label's contextmenu's Combobox has generated this event?
Upvotes: 1
Views: 3513
Reputation: 1
private void OnMenuItemClick(object sender, EventArgs e)
{
var mnItem = sender as MenuItem;
Control c = mnItem.Parent.GetContextMenu().SourceControl;
if(c == neefullControl)
{
...
}
}
Upvotes: -1
Reputation: 8907
You can get the ComboBox from the sender
argument in the eventhandler.
You can then get the ContextMenu from the Parent
property on the ComboBox.
And then finally the Label from the PlacementTarget
property on the ContextMenu.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var label = new Label();
label.Content = "Click me!";
label.Name = "clickMe";
this.Content = label;
var cmb = new ComboBox();
cmb.Name = "combobox1";
cmb.Items.Add("Test1");
cmb.Items.Add("Test2");
cmb.Items.Add("Test3");
cmb.SelectionChanged += new SelectionChangedEventHandler(cmb_SelectionChanged);
var menu = new ContextMenu();
menu.Name = "contextmenu";
menu.Items.Add(cmb);
label.ContextMenu = menu;
}
private void cmb_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var cmb = (ComboBox)sender;
var contextmenu = (ContextMenu)cmb.Parent;
var label = (Label)contextmenu.PlacementTarget;
MessageBox.Show("Combobox: " + cmb.Name + Environment.NewLine +
"Contextmenu: " + contextmenu.Name + Environment.NewLine +
"Label: " + label.Name);
}
}
Upvotes: 3