WPF - Need a combination of Tree+Grid, with Context Menu

独自空忆成欢 提交于 2020-01-24 22:44:05

问题


My application is implemented by a GridView inside a TreeList.

Much to my despair, I discovered that the GridView is very primitive, compared to the widely used DataGrid. I am considering these two options:

(1) Somehow, I replace the GridView with a DataGrid (which supports Context Menu).

(2) Somehow, I add the Context Menu capability to the existent GridView.

Which of the 2 approaches (or another?) would you recommend?

Source code is much appreciated.

TIA.


回答1:


Based on the linked code, here is the solution:

1 - Add the ContextMenu as a Resource:

<Window.Resources>
    <ContextMenu x:Key="ItemsContextMenu" x:Shared="False">
        <MenuItem>
            <MenuItem.Header>
                <TextBlock>
                    <Run>Context Menu Action for Item</Run>
                    <Run Text="{Binding Tag.Name}"/>
                </TextBlock>
            </MenuItem.Header>
        </MenuItem>
    </ContextMenu>

    <!-- other stuff here -->

</Window.Resources>

It is recommended that you set x:Shared="False" to prevent Binding issues related to reusing the resource instance.

2 - Define an ItemContainerStyle for your TreeList that sets the ContextMenu for the TreeListItems:

<tree:TreeList ...>
    <!-- other stuff here -->

    <tree:TreeList.ItemContainerStyle>
        <Style TargetType="{x:Type tree:TreeListItem}">
            <Setter Property="ContextMenu" Value="{StaticResource ItemsContextMenu}"/>
         </Style>
    </tree:TreeList.ItemContainerStyle>
</tree:TreeList>

Notice that I'm using DataBinding in the ContextMenu, which means you have a proper, working DataContext in it. You should be able to use Commands and other stuff in it.



来源:https://stackoverflow.com/questions/24435039/wpf-need-a-combination-of-treegrid-with-context-menu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!