This may be a good candidate for AttachedProperty . Basically, what would you do is wrap ContextMenu in UserControl and then add the dependency property to UserControl. For instance:
MyContextMenu.xaml
<UserControl x:Class="MyContextMenu" ...> <UserControl.Template> <ContextMenu ItemSource="{Binding}" /> </UserControl.Template> </UserControl>
MyContextMenu.xaml.cs
public static readonly DependencyProperty MenuItemsSourceProperty = DependencyProperty.RegisterAttached( "MenuItemsSource", typeof(Object), typeof(MyContextMenu), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender) ); public static void SetMenuItemsSource(UIElement element, Boolean value) { element.SetValue(MenuItemsSourceProperty, value);
Window1.xaml
<Window ...> <Window.Resources> <DataTemplate TargetType="ListViewItem"> <Border MyContextMenu.MenuItemsSource="{Binding Orders}"> <Border> </DataTemplate> </Window.Resources> <local:MyContextMenu /> <Button MyContextMenu.MenuItemsSource="{StaticResource buttonItems}" /> <ListView ... /> </Window>
VisualTreeHelpers
public static IEnumerable<DependencyObject> GetVisuals(this DependencyObject root) { int count = VisualTreeHelper.GetChildrenCount(root); for (int i = 0; i < count; i++) { var child = VisualTreeHelper.GetChild(root, i); yield return child; foreach (var descendants in child.GetVisuals()) { yield return descendants; } } } public static DependencyObject GetRoot(this DependencyObject child) { var parent = VisualTreeHelper.GetParent(child) if (parent == null) return child; return parent.GetRoot(); }
This example has not been verified. I will look later tonight and make sure it is accurate.
source share