DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Binding A Command In A ContextMenu

  • submit to reddit
        // (1) Use DataContext of the PlacementTarget
// (2) For multiple commands, have to use a "ValueBag" converter (that just holds the values in a list)
// (3) MultiValueConverter simply returns a list of the objects provided

<ContextMenu DataContext="{Binding Path=PlacementTarget.DataContext, RelativeSource={RelativeSource Mode=Self}}" >
	<MenuItem DataContext="{Binding}"
			Header="New Layout Element..."
			Command="{Binding Path=SomeCommand}" />


<TextBlock ... >
		<MultiBinding Converter="{StaticResource ValueBag}">
			<Binding Path="." />
			<Binding Path="DataContext.SomeCommand1" />
			<Binding Path="DataContext.SomeCommand2" />
		<ContextMenu DataContext="{Binding Path=PlacementTarget.DataContext, RelativeSource={RelativeSource Mode=Self}}">
			<MenuItem Header="Menu Item 1..."
								Command="{Binding Path=[1]}"
								CommandParameter="{Binding Path=[0]}" />
			<MenuItem Header="Menu Item 2"
								Command="{Binding Path=[2]}"
								CommandParameter="{Binding Path=[0]}" />


return new List<object>(values);