0

Same question: WPF ContextMenu with ItemsSource - how to bind to Command in each item?

I tried implementing it as below but no dice.

Currently have in my XAML:

<DataGrid.ContextMenu>
            <ContextMenu ItemsSource="{Binding Users}">
                <ContextMenu.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=UID, Converter={StaticResource UserConverter}}"/>
                    </DataTemplate>
                </ContextMenu.ItemTemplate>
                <ContextMenu.ItemContainerStyle>
                    <Style TargetType="MenuItem">
                        <Setter Property="Command" Value="{Binding ReassignFileCommand}" />
                    </Style>
                </ContextMenu.ItemContainerStyle>
            </ContextMenu>
        </DataGrid.ContextMenu>

Command does work if I use:

            <DataGrid.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Woooo" Command="{Binding ReassignFileCommand}" />
            </ContextMenu>
        </DataGrid.ContextMenu>

Needed to change to (Solution):

<Setter Property="Command" Value="{Binding Path=DataContext.ReassignFileCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}" />
Community
  • 1
  • 1
Omar Mir
  • 1,500
  • 1
  • 19
  • 39

1 Answers1

1

DataContext of MenuItem is corresponding object from Users collection, not the object with Users property which is DataContext of your ContextMenu. Most likely your command is implemented in that ContextMenu datacontext class so WPF can't find it. Such bindings errors can be easily found in output window in debug mode (http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/30/debugging-data-bindings-in-a-wpf-or-silverlight-application.aspx)

You can fix this by movind your command to user class or to change your binding to point to correct class (by binding to datacontext of contextMenu with ElementName or RelativeSource)

Nikolay
  • 3,658
  • 1
  • 24
  • 25
  • You were right but I tried: Also tried ContextMenu as x:Type Still get: BindingExpression path error: 'ReassignFileCommand' property not found on 'object' ''DataGrid' (Name='ui_dtgAgreements')' – Omar Mir Apr 11 '12 at 22:12
  • It should be `Value="{Binding DataContext.ReassignFileCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}, AncestorLevel=1}}" ` – Nikolay Apr 12 '12 at 05:55