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 element is
‘MenuItem’ (Name=”); target property is ‘IsEnabled’ (type ‘Boolean’)
In the Output window of visual studio and my code doesnt do what it is supposed to do.
The add works fine because it is never needing to be disabled but the remove is not being disabled.
<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>
Where the converter simply takes returns true if there is no object and false if it exists.
I have tried moving this code in and out of the grid as well as moving parts of the binding in different orders. When I run the the code and put in a break point, it never went into the code for the boolean converter. Why cant it see the grid when it is inside it?
A ContextMenu is opened on a different Visual Tree then his parent, and therefore Named Binding won’t work.
Try something like this:
Which uses the ContextMenu’s
PlacementTarget(which is the DataGrid) to get the correct DataContext.Another option is to set the
NameScopefor the ContextMenu. Add the following line to your CodeBehind:Where
contextMenuis the Name you gave your ContextMenu