WPF MenuItem IsChecked绑定不起作用

编程入门 行业动态 更新时间:2024-10-26 23:40:53
本文介绍了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查找切换按钮,请参见 blogs.msdn/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 blogs.msdn/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:

System.Windows.Data错误:4:找不到与之绑定的源 参考"ElementName = toggleButton". BindingExpression:Path = IsChecked; DataItem = null;目标元素是 'MenuItem'(Name ='menuItemBlock');目标属性是"IsChecked" (输入布尔值")

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')

要解决此问题,请使用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绑定不起作用

本文发布于:2023-11-10 06:04:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574549.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   不起作用   WPF   MenuItem   IsChecked

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!