WPF MenuItem IsChecked Binding not working

Does anyone know why menu item binding does not work?

<ToggleButton Name="toggleButton" Checked="checkBoxPublish_Checked" > <ToggleButton.Resources> <converters:BooleanToHiddenVisibility x:Key="boolToVis"/> </ToggleButton.Resources> <Grid> <Image Height="auto" HorizontalAlignment="Left" Margin="5" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="auto" /> <Viewbox > <TextBlock Text="Blocked" Opacity="0.7" Foreground="Red" Visibility="{Binding Path=IsChecked, ElementName=toggleButton, Converter={StaticResource boolToVis}}"/> </Viewbox> </Grid> <ToggleButton.ContextMenu> <ContextMenu StaysOpen="True" > <MenuItem x:Name="menuItemBlock" Header="Block" Click="menuItemClick" IsCheckable="True" IsChecked="{Binding ElementName=toggleButton, Path=IsChecked}"/> <MenuItem x:Name="menuItemIgnorePtz" Header="Ignore Ptz" Click="menuItemClick" IsCheckable="True" /> </ContextMenu> </ToggleButton.ContextMenu> </ToggleButton> 
+7
wpf menuitem
source share
1 answer

I assume this is the context menu that you come across using data binding.

The toggler is not in the logical tree of the context menu, so he cannot find the togglebotton button using ElementName, see http://blogs.msdn.com/b/mikehillberg/archive/2008/05/23/of-logical-and -visual-trees-in-wpf.aspx

This is why you get an error for this binding in your output window in VS:

Error System.Windows.Data: 4: Cannot find source for binding with reference 'ElementName = toggleButton'. BindingExpression: Path = IsChecked; DataItem = NULL; target element 'MenuItem' (Name = 'menuItemBlock'); target is is IsChecked - (type 'Boolean')

To fix, find the toggle button using FindAncestor:

 <MenuItem Header="Block" IsCheckable="True" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ContextMenu}, Path=PlacementTarget.IsChecked}" /> 
+8
source share

All Articles