2016-03-14 85 views
0

好吧,伙计们。我已经尝试了大约3天,并没有任何数量的谷歌搜索帮助。下面是我的XAML的片段(应该足以跟上)。 我的问题是“ContextMenu”的命令。 正如你所见,我有DeleteTagCommand。现在,如果我把它放在CheckBoxCommand的位置上,那么这个命令就可以工作,这很棒..但是它只是在当前位置被调用,而且它让我疯狂。绑定命令 - 祖先

 <ScrollViewer Grid.Column="0"> 
      <StackPanel Orientation="Vertical"> 
       <ItemsControl ItemsSource="{Binding Tags, UpdateSourceTrigger=PropertyChanged}"> 
        <ItemsControl.ItemTemplate> 
         <DataTemplate> 
          <CheckBox Content="{Binding Value}" Margin="10,5,10,5" Command="{Binding DataContext.CheckBoxCommand, 
                          RelativeSource={RelativeSource FindAncestor, 
                          AncestorType={x:Type Grid}}}" 
            CommandParameter="{Binding }"> 
           <CheckBox.ContextMenu> 
            <ContextMenu> 
             <MenuItem Header="Delete" Command="{Binding DataContext.DeleteTagCommand, 
                        RelativeSource={RelativeSource FindAncestor, 
                        AncestorType={x:Type Grid}}}" 
                CommandParameter="{Binding}" /> 
            </ContextMenu> 
           </CheckBox.ContextMenu> 
          </CheckBox> 
         </DataTemplate> 
        </ItemsControl.ItemTemplate> 
       </ItemsControl> 
      </StackPanel> 
     </ScrollViewer> 

我已经试过:

  • 来自全国各地的演出呼唤“的ElementName”,但它从来没有被拾起
  • 更改“AncestorLevel”淫秽号码,希望是问题
  • 以及更多......

不知道什么是对你有用的家伙,但下面是输出消息我得到

找不到与参考'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.Grid',AncestorLevel ='1'绑定的源代码。 BindingExpression:路径= DataContext.DeleteTagCommand;的DataItem = NULL;目标元素是'MenuItem'(Name ='');目标属性是“命令”(类型“的ICommand”)

感谢

回答

2

ContextMenus实际上不是相同的视觉树作为他们的父母,使他们不能直接绑定到其中的任何元素的一部分。但是,它们仍然可以绑定到StaticResources。诀窍是使用中间代理,如BindingProxy class shown on this page。通过添加一个实例你ItemsControl资源块开始:

<ItemsControl.Resources> 
    <local:BindingProxy x:Key="Proxy" Data="{Binding}" /> 
</ItemsControl.Resources> 

然后用它来绑定你ContextMenu命令:

<ContextMenu> 
    <MenuItem Header="Delete" Command="{Binding Data.DeleteTagCommand, Source={StaticResource Proxy}}" CommandParameter="{Binding}" /> 
</ContextMenu> 
+0

谢谢。这是我讨厌WPF的原因之一。再次,谢谢:) – Oyyou