After migrating from version 8.0 to version 9.0, I am getting error messages related to the binding of menu items. I am working with Visual Studio 17.12.3 and .NET Core 9.0.101 on a Windows 11 (23H2) machine. Further down in the XAML code, I have the same binding in a button, which does not generate any errors. The XAML code is from a WPF project built using MVVM, with no code-behind. When I revert to version 8.0, everything works fine again. Is something changed for the menuitems?
The ERROR is: System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Window', AncestorLevel='1''. BindingExpression:Path=DataContext.BttnLeeg; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')
The code that works (RelativeSource Binding of the Button):
<Button Height="18" Width="18" HorizontalAlignment="Right"
ToolTip="{Binding DataContext.BttnRemoveConnection_ToolTip, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
Command="{Binding DataContext.BttnRemoveConnection, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
CommandParameter="{Binding RetourValue}"
Visibility="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.ShowBttn}">
<DockPanel LastChildFill="True" Width="18" Height="18">
<TextBlock Text="{Binding DataContext.BttnRemoveConnection_Content, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" Style="{StaticResource RemoveLink_Background}" Margin="0,0,0,0" />
<TextBlock Text="{Binding DataContext.BttnRemoveConnection_Content_Info, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" Style="{StaticResource RemoveLink_Foreground}" Margin="-16,-4,0,0" />
</DockPanel>
</Button>
The code with the ERROR (just one menu item, of the 5 in the original code):
<UserControl.Resources>
<ContextMenu x:Key="MyContextMenu" x:Shared ="true" Background="DarkGray" Foreground="Black" >
<MenuItem Header="Leeg" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.BttnLeeg}" CommandParameter="{Binding Path=PlacementTarget, RelativeSource={RelativeSource AncestorType=ContextMenu}}" Height="24" />
</ContextMenu>
</UserControl.Resources>