如何为ContextMenu设置TreeViewItem的DataContext

时间:2012-06-26 07:02:54

标签: c# wpf data-binding

我有以下代码。我试图将Command的{​​{1}}属性绑定到在用户控件的MenuItem中实现的相关命令。谁能帮我?该命令无法执行。

DataContext

2 个答案:

答案 0 :(得分:4)

请试试这个:

<TreeView.ItemTemplate>
    <HierarchicalDataTemplate DataType="model:Item"
                              ItemsSource="{Binding Children}">
        <Grid Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=UserControl}}">
            <Grid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Add Category"
                              Command="{Binding Path=PlacementTarget.Tag.AddEntityCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
                </ContextMenu>
            </Grid.ContextMenu>
            <TextBlock Text="{Binding Description}" Margin="0,0,10,0" />
        </Grid>
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>

答案 1 :(得分:0)

您可以在绑定中使用RelativeSource来查找父对象 例如

<MenuItem Header="Add Root Category" Command="{Binding DataContext.CommandName, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}/>