code_junkie

How do I handle click events in a data bound menu in WPF

Nov 12th, 2011
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. <Window x:Class="WPFDataBoundMenu.Window1"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. Title="Window1" Height="300" Width="300">
  5. <Grid>
  6. <Menu>
  7. <MenuItem Header="File" Click="MenuItem_Click" />
  8. <MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}" />
  9. </Menu>
  10. </Grid>
  11.  
  12. using System.Collections.Generic;
  13. using System.Windows;
  14.  
  15. namespace WPFDataBoundMenu
  16. {
  17. /// <summary>
  18. /// Interaction logic for Window1.xaml
  19. /// </summary>
  20. public partial class Window1 : Window
  21. {
  22. public List<string> MyMenuItems { get; set;}
  23.  
  24. public Window1()
  25. {
  26. InitializeComponent();
  27. MyMenuItems = new List<string> { "Item 1", "Item 2", "Item 3" };
  28. DataContext = this;
  29. }
  30.  
  31. private void MenuItem_Click(object sender, RoutedEventArgs e)
  32. {
  33. MessageBox.Show("how do i handle the other clicks?!");
  34. }
  35. }
  36. }
  37.  
  38. <MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}" Click="DataBoundMenuItem_Click" />
  39.  
  40. private void DataBoundMenuItem_Click(object sender, RoutedEventArgs e)
  41. {
  42. MenuItem obMenuItem = e.OriginalSource as MenuItem;
  43. MessageBox.Show( String.Format("{0} just said Hi!", obMenuItem.Header));
  44. }
  45.  
  46. <MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}">
  47. <MenuItem.ItemContainerStyle>
  48. <Style TargetType="MenuItem">
  49. <Setter Property="Command" Value="{x:Static local:MyCommands.MyCommand}"/>
  50. <Setter Property="CommandParameter" Value="{Binding SomeProperty}"/>
  51. </Style>
  52. </MenuItem.ItemContainerStyle>
  53. </MenuItem>
Add Comment
Please, Sign In to add comment