本文介绍了WPF MenuItem IsChecked绑定不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人知道为什么菜单项绑定不起作用吗?
<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>
推荐答案
我猜测这是您使用数据绑定时遇到的上下文菜单.
I'm guessing that it is the contextmenu you have problem using data binding with.
切换按钮不在上下文菜单的逻辑树中,因此无法使用ElementName查找切换按钮,请参见 http://blogs.msdn.com/b/mikehillberg/archive/2008/05/23/of- wpf.aspx中的逻辑和可视树
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
这就是为什么您在VS的输出窗口中收到该绑定错误的原因:
That is why you get an error for that binding in your output window in VS:
要解决此问题,请使用FindAncestor查找切换按钮:
To fix, look up the toggle button using FindAncestor:
<MenuItem
Header="Block"
IsCheckable="True"
IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ContextMenu}, Path=PlacementTarget.IsChecked}" />
这篇关于WPF MenuItem IsChecked绑定不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!