在 MenuItem HeaderTemplate 内使用 ContentPresenter 会导致 StackOverflowException
请注意以下标记:
<Style TargetType="{x:Type MenuItem}" x:Key="...">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<ContentPresenter />
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
当将此样式添加到应用程序标记文件时,运行时会发生 StackOverflowException
。
该样式应用于附加到 TreeViewItem
的 ContextMenu
的菜单项(或用于生成树内容的后续 DataTemplate
);当释放鼠标右键并且上下文菜单即将打开时,会引发异常。
ContextMenu
的用例之一是:
<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>
异常已被隔离到标头模板内的
标记。注释掉它可以清除异常。这是怎么回事?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信
ContentPresenter
包含整个MenuItem
,因此您基本上是在设置嵌套尝试使用类似
;
(这可能不是确切的语法,但您基本上希望绑定到ContentPresenter
的Content
部分,而不是整个内容)I believe
ContentPresenter
holds the entireMenuItem
, so you're basically setting up nestedTry using something like
<ContentPresenter Content="{TemplateBinding Content}" />
(That might not be the exact syntax, but you basically want to bind to theContent
part of theContentPresenter
, not the entire thing)