Setting a DataContext for ContextMenu in ItemsControl.DataTemplate

I have a custom control that is used in the data template for the ItemsControl. I want to put ContextMenu on each element and call it to view the UserControl View Model command. Using the XAML below, I can get click events on a custom control to call SelectedItemCommand in the view model of the user control. But, using a similar syntax for the context menu fails. By default, I get a view mode for each custom control. Any RelativeSource syntax value that I use is not permitted for the RelativeSource Self view model.

What is the magic code?

        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <controls:MyCustomItem Width="Auto"
                                                 Command="{Binding DataContext.SelectedItemCommand,
                                                                   RelativeSource={RelativeSource FindAncestor,
                                                                                                  AncestorType={x:Type ItemsControl}}}"
                                                 CommandParameter="{Binding}">
                    <controls:MyCustomItem.ContextMenu>
                        <ContextMenu>
                            <MenuItem Command="{Binding DataContext.ClearAlarmsCommand,
                                                        RelativeSource={RelativeSource FindAncestor,
                                                                                       AncestorType={x:Type ItemsControl}}}"
                                      Header="Clear All" />
                        </ContextMenu>
                    </controls:MyCustomItem.ContextMenu>
                </controls:MyCustomItem>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
+4
1

ContextMenu doesn't lie in same Visual Tree ItemsControl. , RelativeSource ElementName Binding, , .

WPF 4.0 , x:Reference DataConttext ItemsControl.

x:Name ItemsControl x:Reference :

<ItemsControl x:Name="itemsControl">
   ....
   <MenuItem Command="{Binding DataContext.ClearAlarmsCommand,
                               Source={x:Reference itemsControl}}"
             Header="Clear All" />
   ....
</ItemControl>

Freezable BindingProxy, WPF 4.0. .

+9

All Articles