WPF - Need a combination of Tree+Grid, with Contex

2019-07-27 07:44发布

问题:

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.