Question

Please observe the following markup:

<Style TargetType="{x:Type MenuItem}" x:Key="...">
    <Setter Property="HeaderTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <ContentPresenter />
                    </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

When this style is added to the application markup file, a StackOverflowException occurs at runtime.

The style is being applied to the menu items of a ContextMenu which is attached to a TreeViewItem (or a subsequent DataTemplate for generated tree content); The exception throws when the right mouse button is released and the context menu is due to open.

One of the use cases for the ContextMenu is:

<DataTemplate x:Key="TviChaptersHeaderTemplate">
<StackPanel Orientation="Horizontal" Margin="0,2,0,2">
    <Image Margin="2,0,0,0" Width="16" Height="16" Source="\Icons\pages.png" />
            <TextBlock Text="{Binding}" Margin="5,0" />

    <StackPanel.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Add Chapter" 
                              Style="{StaticResource STYLE}" />
                </ContextMenu>
            </StackPanel.ContextMenu>
</StackPanel>
</DataTemplate>

The exception has been isolated to the <ContentPresenter /> tag inside the header template. Commenting it out clears the exception. What's going on here?

Was it helpful?

Solution

I believe ContentPresenter holds the entire MenuItem, so you're basically setting up nested

<MenuItem>
    <Header>
        <MenuItem>
            <Header>
                ... etc. 

Try using something like <ContentPresenter Content="{TemplateBinding Content}" /> (That might not be the exact syntax, but you basically want to bind to the Content part of the ContentPresenter, not the entire thing)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top