有人知道为什么菜单项绑定不起作用吗?
<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绑定不起作用
发布评论