我有一个源自Button控件的自定义按钮。此自定义按钮(GlyphButton)XAML页面声明了一种指定控件模板的样式,如下所示:
<Button x:Class="Foo.Presentation.Controls.GlyphButton">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="OverridesDefaultStyle"
Value="True" />
<Setter Property="SnapsToDevicePixels"
Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="PART_Border"
Padding="1"
Background="Transparent"
BorderThickness="0"
Height="{TemplateBinding Height}"
Width="{TemplateBinding Width}"
BorderBrush="Transparent">
<local:VectorImage x:Name="PART_VectorImage"
Path="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:GlyphButton}}, Path=Path}"
Fill="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:GlyphButton}}, Path=Fill}"
Stretch="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:GlyphButton}}, Path=Stretch}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver"
Value="True">
<Setter TargetName="PART_VectorImage"
Property="Effect">
<Setter.Value>
<DropShadowEffect Color="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:GlyphButton}}, Path=GlowColor, TargetNullValue='Black'}"
ShadowDepth="0"
BlurRadius="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:GlyphButton}}, Path=GlowRadius}"
Opacity="1.0" />
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
我在整个应用程序中使用此控件。在一个实例中,我需要添加一个带有自定义样式的上下文菜单,以便在鼠标左键单击时显示菜单,以便我想出以下内容:
<controls:GlyphButton Height="24"
Width="24"
Path="{StaticResource HamburgerMenu4}"
Fill="{StaticResource BlueGradientBrush}">
<controls:GlyphButton.Style>
<Style TargetType="{x:Type controls:GlyphButton}" BasedOn="{StaticResource {x:Type controls:GlyphButton}}">
<Style.Triggers>
<EventTrigger RoutedEvent="Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0"
Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
</Style>
</controls:GlyphButton.Style>
在运行时,我得到一个异常,说明当我包含上面显示的BasedOn属性时,Xaml解析器找不到名为'GlyphButton'的样式。我通过声明模板内联而不是使用一种样式来消除了将最低级别样式基于任何东西的需要而发现了当前的解决方法。
<GlypButton>
<GlyphButton.Template>
<!-- Template goes here -->
</GlyphButton.Template>
</GlypButton>
我在这里缺少什么?我是不是通过样式声明自定义控件的模板来遵循最佳实践,如果是,为什么会失败?