我有一个 ContextMenu
的隐式样式,是从这个网站上获取的:
<Application.Resources>
<SolidColorBrush x:Key="WindowBackgroundBrush" Color="#FFF" />
<SolidColorBrush x:Key="SolidBorderBrush" Color="#888" />
<Style TargetType="ContextMenu">
<Setter Property="SnapsToDevicePixels" Value="True"/>
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Grid.IsSharedSizeScope" Value="true"/>
<Setter Property="HasDropShadow" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContextMenu">
<Border
Name="Border"
Background="{StaticResource WindowBackgroundBrush}"
BorderBrush="{StaticResource SolidBorderBrush}"
BorderThickness="1" >
<StackPanel IsItemsHost="True"
KeyboardNavigation.DirectionalNavigation="Cycle"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="HasDropShadow" Value="true">
<Setter TargetName="Border" Property="Padding" Value="0,3,0,3"/>
<Setter TargetName="Border" Property="CornerRadius" Value="4"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
然后我尝试在这里使用它,以便它适用于
TextBox
的默认ContextMenu
和我为Button
添加的ContextMenu
。</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Height="30" Width="200">Test</TextBox>
<Button Grid.Row="1" Width="200" Height="30" Content="Test2">
<Button.ContextMenu>
<ContextMenu>
<MenuItem>Test</MenuItem>
<MenuItem>Test2</MenuItem>
</ContextMenu>
</Button.ContextMenu>
</Button>
</Grid>
这个样式被应用于Button
,但没有被应用于TextBox
。
我觉得这应该很简单明了,为什么我的隐式样式没有被应用到TextBox
的默认ContextMenu
上,我做错了什么?
==更新==
我目前不确定答案,但我认为这里的问题在于TextBox
与ContextMenu
的设计存在一些缺陷,希望有更专业知识的人能够确认。
使用Snoop,我可以看到ContextMenu
不是你所期望的对象,而是一个内部的EditorContextMenu
对象,因此你无法对其进行样式设置。他们为什么要这样做呢?我不知道。
作为解决方法,我创建了一个默认的上下文菜单并使用它。如果你给TextBox
添加一个上下文菜单,它就会正确地采用隐式样式。
由于你知道默认ContextMenu
中的项,而这些项基本上使用ApplicationCommands,所以非常简单:
<ContextMenu x:Key="DefaultContextMenu">
<MenuItem Command="ApplicationCommands.Copy" />
<MenuItem Command="ApplicationCommands.Cut" />
<MenuItem Command="ApplicationCommands.Paste" />
</ContextMenu>
然后在您的TextBoxStyle中执行以下操作:
<Style x:Key="MyTextBoxStyle" TargetType="TextBox">
<Setter Property="ContextMenu" Value="{StaticResource DefaultContextMenu}" />
使用这个方法,您的
TextBox
的默认ContextMenu
将采用隐式样式。
<Style TargetType="ContextMenu" BasedOn="{StaticResource {x:Type ContextMenu}}" />
。你只需要把basedon的值更改为你新样式的引用,就可以将其作为全局默认值了。 - Chris W.ContextMenu
:<Style TargetType="ContextMenu">
。我尝试将其添加到不同的级别,但它在任何级别都不起作用。 - Dzyann