WPF MenuItem IsChecked Binding not working

Kaya picture Kaya · May 25, 2010 · Viewed 9.7k times · Source

Anyone know why the 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>

Answer

Wallstreet Programmer picture Wallstreet Programmer · May 25, 2010

I'm guessing that it is the contextmenu you have problem using data binding with.

The togglebutton is not in the logical tree of the contextmenu so it can't find the togglebutton using ElementName, see http://blogs.msdn.com/b/mikehillberg/archive/2008/05/23/of-logical-and-visual-trees-in-wpf.aspx

That is why you get an error for that binding in your output window in VS:

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

To fix, look up the toggle button using FindAncestor:

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