Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an click event to a programatically added menu item

I am working on a C# WPF project and I am storing some items in an SQLite database, when the program loads, it then retrieves the items from the database and adds the items to the menu. What I then need to do is to allow the user to click on one of the added menu items and something is done based on what was clicked. I can't find anything on how to do this, below is the code for how I am adding the menu item to the menu programatically.

StoredDBConnectionManager storedDbConnectionManager = new StoredDBConnectionManager(Properties.Settings.Default.app_dbPassword);
List<string> connections = storedDbConnectionManager.getStoredConnections();

foreach (string connection in connections)
{
      mnuFileDBConnections.Items.Add(connection);
}

Thanks for any help you can provide.

like image 491
Boardy Avatar asked Jan 17 '26 18:01

Boardy


1 Answers

Here's an example:

XAML:

<Menu Height="23" HorizontalAlignment="Left" Name="menu1" VerticalAlignment="Top" Width="200" />

Code behind:

public MainWindow() {
    InitializeComponent();

    MenuItem item = new MenuItem { Header = "test" };
    item.Click += new RoutedEventHandler(item_Click);
    menu1.Items.Add(item);
}

public void item_Click(Object sender, RoutedEventArgs e) {
    MessageBox.Show("Hello!");
}
like image 84
Steve Avatar answered Jan 20 '26 08:01

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!