【问题标题】:How to bind command into a context menu that is inside TreeView on it's items?如何将命令绑定到其项目上 TreeView 内的上下文菜单中?
【发布时间】:2016-07-27 11:20:42
【问题描述】:

我希望能够通过单击上下文菜单中的命令对 TreeView 内的项目执行命令。更具体地说,仅当项目属于某种类型时(xxTreeViewItem 是具有 2 个子类型的接口)。

   <Grid Name="Root" commonExtensions:EnterKeyUpdateExtension.IsEnabled="True">

    <StackPanel Orientation="Vertical" Grid.Row="0">
        <Button Content="Center on" Command="{Binding Path=CenterOnCommand}" Margin="5,10,5,0"/>
    </StackPanel>
        <Grid>
            <TreeView Grid.Row="0" Name="xxTreeView" DataContext="{Binding Path=xxViewModel}" ItemsSource="{Binding Path=Items}">
                <TreeView.ItemContainerStyle>
                    <Style TargetType="{x:Type TreeViewItem}">
                        <Setter Property="ContextMenu">
                            <Setter.Value>
                                <ContextMenu>
                                    <MenuItem Header="Center On" Command="{Binding CenterOnCommand}"/>
                                </ContextMenu>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </TreeView.ItemContainerStyle>
                <TreeView.ItemTemplate>
                    <HierarchicalDataTemplate ItemsSource="{Binding Path=Items}" DataType="{x:Type localViewItems:xxTreeViewItem}">
                        <TextBlock Text="{Binding Name}" VerticalAlignment="Center"/>
                    </HierarchicalDataTemplate>
                </TreeView.ItemTemplate>
            </TreeView>

顶部按钮中的命令有效,但在上下文菜单中无效。我尝试了几种绑定并找到了祖先,但都没有奏效。有没有唯一的 XAML 解决方案?

【问题讨论】:

    标签: c# wpf binding treeview command


    【解决方案1】:

    ContextMenu 不属于可视化树,因此它不会继承您的 TreeView 的 DataContext。因此,您需要使用 PlacementTarget 属性将其传递给您的 ContextMenu:

    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource AncestorType=TreeView}, Path=DataContext}"></Setter>
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
                        <MenuItem Header="Center On" Command="{Binding CenterOnCommand}" />
                    </ContextMenu>
                </Setter.Value>
            </Setter>
        </Style>
    </TreeView.ItemContainerStyle>
    

    希望对你有帮助

    【讨论】:

    • 还是不行,命令CenterOnCommand在xxEditorViewModel中。 TreeView 中使用的 xxViewModel 是 xxEditorViewModel 的一个属性。通过将 Setter 的 AncestorType 设置为 UserControl(顶部)来解决它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-05-08
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多