Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf tabitem header context menu

Tags:

tabcontrol

How do I add a context menu to wpf tabitem that only appears when I click on tabitem header and not the content? I also need to create tabitems dynamically in .cs so doing this statically in .xaml won't work.

I've tried adding context menu to tabitem.header but it has some problems where if I have [tabitem 1][tabitem2 ] [tabitemtabitemtabitemta]

[tabitem2 ] is stretched to match the width of tabcontrol. any help would be appreciated.

Thanks!

like image 330
user156144 Avatar asked Feb 23 '23 22:02

user156144


1 Answers

See this question for how to do it programmatically. The trick is to set the ContextMenu on whatever control you set as the header content. If you're just using the header to set a simple string value, that won't work. At minimum you'll need to create a TextBlock or ContentControl or something.


For those interested in how to do it via XAML (particularly when using MVVM pattern):

Set a ContextMenu on the TabControl's ItemContainerStyle. It will then only apply to actual tab part (the header) and not the tab content. You can use bindings and such on the MenuItems to get varied behavior based on the specific tab, provided your tab is using a ViewModel..

<TabControl>
    <TabControl.ItemContainerStyle>
        <Style TargetType="{x:Type TabItem}">
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu/> <!-- Define it here! -->
                </Setter.Value>
            </Setter>
        </Style>
    </TabControl.ItemContainerStyle>
</TabControl>
like image 111
Sean Hanley Avatar answered May 25 '23 04:05

Sean Hanley