Guest User

Untitled

a guest
Jun 24th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. <DataTemplate>
  2. <TextBlock Text="{Binding MyInfo}">
  3. <TextBlock.ContextMenu>
  4. <Menu ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.MyContextMenuItems}"/>
  5. </TextBlock.ContextMenu>
  6. </TextBlock>
  7. </DataTemplate>
  8.  
  9. <UserControl x:Class="MyContextMenu" ...>
  10. <UserControl.Template>
  11. <ContextMenu ItemSource="{Binding}" />
  12. </UserControl.Template>
  13. </UserControl>
  14.  
  15. public static readonly DependencyProperty MenuItemsSourceProperty = DependencyProperty.RegisterAttached(
  16. "MenuItemsSource",
  17. typeof(Object),
  18. typeof(MyContextMenu),
  19. new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender)
  20. );
  21. public static void SetMenuItemsSource(UIElement element, Boolean value)
  22. {
  23. element.SetValue(MenuItemsSourceProperty, value);
  24. // assuming you want to change the context menu when the mouse is over an element.
  25. // use can use other events. ie right mouse button down if its a right click menu.
  26. // you may see a perf hit as your changing the datacontext on every mousenter.
  27. element.MouseEnter += (s, e) => {
  28. // find your ContextMenu and set the DataContext to value
  29. var window = element.GetRoot();
  30. var menu = window.GetVisuals().OfType<MyContextMenu>().FirstOrDefault();
  31. if (menu != null)
  32. menu.DataContext = value;
  33. }
  34. }
  35. public static Object GetMenuItemsSource(UIElement element)
  36. {
  37. return element.GetValue(MenuItemsSourceProperty);
  38. }
  39.  
  40. <Window ...>
  41. <Window.Resources>
  42. <DataTemplate TargetType="ListViewItem">
  43. <Border MyContextMenu.MenuItemsSource="{Binding Orders}">
  44. <!-- Others -->
  45. <Border>
  46. </DataTemplate>
  47. </Window.Resources>
  48. <local:MyContextMenu />
  49. <Button MyContextMenu.MenuItemsSource="{StaticResource buttonItems}" />
  50. <ListView ... />
  51. </Window>
  52.  
  53. public static IEnumerable<DependencyObject> GetVisuals(this DependencyObject root)
  54. {
  55. int count = VisualTreeHelper.GetChildrenCount(root);
  56. for (int i = 0; i < count; i++)
  57. {
  58. var child = VisualTreeHelper.GetChild(root, i);
  59. yield return child;
  60. foreach (var descendants in child.GetVisuals())
  61. {
  62. yield return descendants;
  63. }
  64. }
  65. }
  66.  
  67. public static DependencyObject GetRoot(this DependencyObject child)
  68. {
  69. var parent = VisualTreeHelper.GetParent(child)
  70. if (parent == null)
  71. return child;
  72. return parent.GetRoot();
  73. }
Add Comment
Please, Sign In to add comment