【发布时间】:2011-03-30 22:47:08
【问题描述】:
我有一个非常简单的TabItem 模板和一个MultiTrigger,在一个Condition 上使用了SourceName 属性。以下 XAML 在启动时会抛出 NullReferenceException,但没有帮助我解决问题的有用信息。
最奇怪的是,如果您删除 SourceName 属性,代码会运行得很好。或者,如果您保留SourceName 属性,但删除MultiTrigger.EnterActions 并改用标准Setters,那么它也可以正常工作。只有SourceName 属性和MultiTrigger.EnterActions 的组合会抛出NullReferenceException,没有明显的原因。那么这有什么问题呢?
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" WindowStartupLocation="CenterScreen">
<Window.Resources>
<Style TargetType="TabItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabItem">
<ControlTemplate.Resources>
<Storyboard x:Key="Storyboard_TabItem_Hover">
<DoubleAnimationUsingKeyFrames Storyboard.TargetName="background" Storyboard.TargetProperty="Opacity">
<SplineDoubleKeyFrame KeyTime="00:00:00.3" Value="0.1" />
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</ControlTemplate.Resources>
<Border x:Name="background" BorderBrush="Red" BorderThickness="1" Background="Yellow">
<Label Grid.Column="1" Content="{TemplateBinding Header}" />
</Border>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="True" SourceName="background" />
<Condition Property="IsSelected" Value="False" />
</MultiTrigger.Conditions>
<MultiTrigger.EnterActions>
<BeginStoryboard x:Name="sbHover" Storyboard="{StaticResource Storyboard_TabItem_Hover}"/>
</MultiTrigger.EnterActions>
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<TabControl Margin="10">
<TabItem Header="Tab 1" />
<TabItem Header="Tab 2" />
<TabItem Header="Tab 3" />
<TabItem Header="Tab 4" />
</TabControl>
</Window>
更新
作为Greg Sansompointed out,有一个使用MultiDataTrigger 和Binding 的简单解决方法。但是,我仍然想知道为什么首先抛出异常。我疯狂地搜索了 Google 和 MSDN,但没有找到任何东西。那么有什么问题呢?
【问题讨论】:
-
您是否找到了不同的解决方案/解释?我对简单的触发器也有类似的问题,如果像 Greg 建议的那样转换为 DataTrigger,可以解决我的问题。它发生在 Visual Studio 2013 的设计器中(运行时很好)。
标签: c# .net wpf exception xaml