Anchor does not search for source with reference (MenuItem)

I am getting the error:

System.Windows.Data error: 4: Cannot find source for binding with reference 'ElementName = gridProductViewDataGrid'. BindingExpression: Path = SelectedItem; DataItem = NULL; target item 'MenuItem' (Name = ''); target is is IsEnabled (type 'Boolean')

In visual studio's output window and my code doesn't do what it is supposed to do.

The add works great because it never needs to be disabled, but the uninstall does not disable.

<DataGrid AutoGenerateColumns="False" IsReadOnly="False" CanUserAddRows="False" CanUserDeleteRows="False" EnableRowVirtualization="True" ItemsSource="{Binding Items, Mode=TwoWay}" x:Name="gridViewProductDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" >
        <DataGrid.ContextMenu>
            <ContextMenu>
                <MenuItem Header="{Binding LabelStrings.AddProductLabel, Source={StaticResource ResourceWrapper}}" Click="Add_Product_MenuItem_Click"/>
                <MenuItem Header="{Binding LabelStrings.RemoveProductLabel, Source={StaticResource ResourceWrapper}}" Click="Remove_Product_MenuItem_Click" IsEnabled="{Binding ElementName=gridViewProductDataGrid, Path=SelectedItem, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource ObjectToBooleanConverter}}"/>
                </MenuItem>
            </ContextMenu>
        </DataGrid.ContextMenu>

      

If the converter simply accepts values, it returns true if there is no object and false if it exists. I've tried moving this code inside and outside the grid, and also moving the anchor parts in different orders. When I run the code and put a breakpoint, it never got into the code for the boolean converter. Why can't he see the mesh when it's inside?

+3


source to share


1 answer


A ContextMenu opens in a different VisualTree, then its parent, and therefore Named Binding won't work.

Try something like this:

IsEnabled="{Binding PlacementTarget.DataContext.SelectedItem, 
                    RelativeSource={RelativeSource FindAncestor,AncestorType=ContextMenu}, 
                    Converter={StaticResource ObjectToBooleanConverter}}"

      

Uses a ContextMenu PlacementTarget

(which is a DataGrid) to get the correct DataContext.



Another option is to set NameScope

for ContextMenu. Add the following line to your CodeBehind:

NameScope.SetNameScope(contextMenu, NameScope.GetNameScope(this));

      

Where contextMenu

is the name you provided in the ContextMenu

+3


source







All Articles