2010-05-25 138 views
7

任何人都知道为什么菜单项绑定不起作用?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> 

回答

8

我猜,这是使用数据绑定与你有问题的文本菜单。

切换按钮是不是在文本菜单的逻辑树,因此无法找到使用的ElementName切换按钮,看到http://blogs.msdn.com/b/mikehillberg/archive/2008/05/23/of-logical-and-visual-trees-in-wpf.aspx

这就是为什么你得到一个错误,在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')

要修复,使用查找切换按钮FindAncestor:

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

当我第一次看到这个,我不知道你有* *绑定到你的DATAS通过ContextMenu.PlacementTarget属性(而不是通过RelativeSource扩展所提供的任何其他内容)访问,因为这是返回包含控件的可视化树的方式。然而,这可能只是我有点慢,我现在已经得到它(并解决了我的问题)。谢谢您的帮助。 +1。 – 2011-02-01 10:30:12