WPF MenuItem IsChecked Binding not working

◇◆丶佛笑我妖孽 提交于 2019-12-10 03:49:05

问题


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>

回答1:


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}" />


来源:https://stackoverflow.com/questions/2904635/wpf-menuitem-ischecked-binding-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!