Aufgabe:
Ich möchte beim Klick auf ein WPF Element ein dynamisches KontextMenü erstellen und anzeigen
Lösung: mit dem WPF Element ContextMenu kann man kleine Menüs als Auswahl direkt über einem Element anzeigen.
C# Code zum Erstellen des ContextMenu
private void Open_ContextMenu(object sender, MouseButtonEventArgs e) { //---------------------< Open_ContextMenu() >---------------------
//< init > //*get values from drag_button_start FrameworkElement element= (FrameworkElement) sender; string sControlname = element.Name; int IDMitarbeiter = clsStrings.get_Key_Value_from_String_as_Integer(sControlname, "IDMitarbeiter"); //</ init >
ContextMenu contextMenu = new ContextMenu(); //< Menu_Items_anfuegen > MenuItem item = new MenuItem(); item.Header = "Krank"; contextMenu.Items.Add(item);
item = new MenuItem(); item.Header = "Urlaub"; contextMenu.Items.Add(item);
item = new MenuItem(); item.Header = "Krank"; contextMenu.Items.Add(item); //</ Menu_Items_anfuegen >
//< anfuegen > //*an wpf Element als contextmenu anfuegen //contextMenu.Visibility = Visibility.Visible; element.ContextMenu = contextMenu; //< anfuegen >
//< anzeigen > contextMenu.IsOpen= true; //< anzeigen >
//*Original-Event ausschalten //*damit der Event nicht durch den original-Mausklick geschlossen wird, muss man den Vorgang beenden e.Handled = true;
//---------------------</ Open_ContextMenu() >--------------------- } |
C# dynamisches Anfügen an den Click-Event
//-< panel >- Border cellBorder = new Border(); Color color = (Color)ColorConverter.ConvertFromString(_sColor_Cell); cellBorder.Background = new SolidColorBrush(color); cellBorder.Margin = new Thickness(1); //cellBorder.MouseDown += CellBorder_Clicked;
//--< Cell_name >-- string sCellBorder_Name = "cellBorder_IDMitarbeiter_" + mitarabeiter.IDMitarbeiter + "_DatePlan_" + sDatePlan ; cellBorder.Name = sCellBorder_Name; cellBorder.MouseLeftButtonDown += new MouseButtonEventHandler(Open_ContextMenu);
|