我正在努力让这个绑定工作在我的ContextMenu上。
我正在使用Items Source,因此每个项目都是frm ItemsSource类型,所以我需要搜索树以获得正确的绑定上下文。
我试图执行的命令存在于ContextMenu的DataContext中,你可以看到它绑定在这里:
DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}"
所以我尝试使用RelativeSource绑定到该数据上下文,但无论我尝试过什么,我总是会遇到绑定错误:
System.Windows.Data Error: 40 : BindingExpression path error: 'CreateNodeCommand' property not found on 'object' ''NodeGraphView' (Name='networkControl')'. BindingExpression:Path=DataContext.CreateNodeCommand; DataItem='ContextMenu' (Name='NodeGraphRightClickMenu'); target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')
以下是代码:
<ContextMenu x:Name="NodeGraphRightClickMenu" DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}" ItemsSource="{Binding DataContext.PolymorphicTypes}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding DataContext.CreateNodeCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"/>
<Setter Property="CommandParameter">
<Setter.Value>
<MultiBinding Converter="{convertersDF:Converter_MultiBindingToArray}">
<Binding Path="."></Binding>
<Binding Path="Name"></Binding>
</MultiBinding>
</Setter.Value>
</Setter>
<Setter Property="Header">
<Setter.Value>
<Binding StringFormat="Create {0}" Path="Name"></Binding>
</Setter.Value>
</Setter>
</Style>
</ContextMenu.ItemContainerStyle>
任何帮助都非常感激。
答案 0 :(得分:0)
答案是如此明显。我需要绑定到DataContext的DataContext。这令人困惑所以我重写了它:
<ContextMenu x:Name="NodeGraphRightClickMenu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}" ItemsSource="{Binding PolymorphicTypes}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding DataContext.CreateNodeCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"/>
<Setter Property="CommandParameter">
<Setter.Value>
<MultiBinding Converter="{convertersDF:Converter_MultiBindingToArray}">
<Binding Path="."></Binding>
<Binding Path="Name"></Binding>
</MultiBinding>
</Setter.Value>
</Setter>
<Setter Property="Header">
<Setter.Value>
<Binding StringFormat="Create {0}" Path="Name"></Binding>
</Setter.Value>
</Setter>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>