基于一些标准的网络搜索,我将我的问题缩小到这个:我相信触发我的故事板的事件在模板被扩展之前被调用。因此,名称是没有意义的,故事板动画所做的名称引用是空的。
如果我不使用 ControlTemplate,这将不是问题。我可以在布局更新后绑定到事件,然后第一次手动调用它。问题解决了。但是,由于这是它自己的资源字典 XAML 文件中的 ControlTemplate,因此我无法使用 C# 来解决此问题。
(更新:我可以肯定地说这不是一个排序问题——换句话说,它与在 ControlTemplate.Resources 或类似之前定义的内容无关。但是,类似的问题可能是由此类排序问题引起的,所以如果您遇到类似的问题,这件事值得调查。有关更详细的解释,请参阅以下在此更新之前所做的答案之一。)
再说一次,我可能完全走错了路。这只是我对幕后发生的事情的理解。为了让您自己判断,这里是实际的例外:
System.InvalidOperationException:
{"'PART_UnderlineBrush' 名称在 'System.Windows.Controls.ControlTemplate' 的名称范围内找不到。"}
这是供参考的样式/模板,删除了所有额外的东西(故事板、属性等)。
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="MetroTabItem" TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Border>
<Border.BorderBrush>
<!-- This is the element that I need to reference, but I am unable to do so. -->
<SolidColorBrush Color="#00ffffff" x:Name="PART_UnderlineBrush" />
</Border.BorderBrush>
<ContentPresenter Content="{TemplateBinding Header}"
ContentTemplate="{TemplateBinding HeaderTemplate}" />
</Border>
<ControlTemplate.Resources>
<Storyboard x:Key="SelectTab">
<!-- This is the animation that will always fail, due to the name reference. -->
<ColorAnimation BeginTime="0:0:0"
Duration="0:0:0.5"
Storyboard.TargetProperty="Color"
Storyboard.TargetName="PART_UnderlineBrush"
To="#ddffffff" />
</Storyboard>
</ControlTemplate.Resources>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="Selector.Selected">
<BeginStoryboard Name="BeginSelected" Storyboard="{StaticResource SelectTab}" />
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>