我想要实现的是在 Storyboard 完成工作时关闭窗口,我尝试在 Storyboard 对象中设置 x:Key 属性,但出现以下错误:“key 属性只能用于包含在IDictionary(例如 ResourceDictionary)”
这是我的代码:
<Window.Resources>
<ControlTemplate x:Key="MyErrorMessage"
TargetType="{x:Type Label}">
<StackPanel Orientation="Horizontal"
Name="ErrorMessage">
<Border CornerRadius="4" Width="Auto"
BorderThickness="0"
VerticalAlignment="Center"
Margin="4,0"
Background="#FF404040"
BorderBrush="Transparent">
<Label Foreground="White"
VerticalAlignment="Center"
Padding="4,2"
Margin="4"
FontWeight="Bold" FontSize="15"
Name="Part1"
Visibility="Visible" HorizontalAlignment="Center" Content="{Binding Message}" />
</Border>
<!-- This TextBlock accepts the content from the parent 'label'. It is not actually displayed, just used to bind data-->
<TextBlock Name="Part3"
Text="{TemplateBinding Content}"
Visibility="Collapsed"></TextBlock>
<!-- This TextBlock binds to the one above and triggers an animation when it gets updated. -->
<!-- Its required because TemplateBinding does not allow NotifyOnTargetUpdate -->
<TextBlock Margin="2"
Name="Part2"
Foreground="Red"
Padding="3"
Visibility="Collapsed"
Text="{Binding ElementName=Part3, Path=Text,NotifyOnTargetUpdated=True}"
VerticalAlignment="Center"></TextBlock>
</StackPanel>
<ControlTemplate.Triggers>
<!-- When Text property of Part2 is blank hide entire control-->
<Trigger SourceName="Part3"
Property="Text"
Value="">
<Setter TargetName="ErrorMessage"
Property="Visibility"
Value="Hidden"></Setter>
</Trigger>
<!-- This trigger is called when Part2 updates which in turn is updated by Part3's databind.
It uses animation to make the label fade away after a few seconds. -->
<EventTrigger SourceName="Part2"
RoutedEvent="Binding.TargetUpdated">
<BeginStoryboard>
<Storyboard TargetName="ErrorMessage" x:Key="gridFadeStoryBoard">
<DoubleAnimation Storyboard.TargetProperty="Opacity" Name="FadeOutAnimation"
Duration="0:0:1.50"
From="1.0"
To="0.0"
BeginTime="0:0:0.50" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Window.Resources>
<StackPanel Orientation="Vertical">
<Label Template="{StaticResource MyErrorMessage}" Name="Label1" />
</StackPanel>
代码隐藏:
private Storyboard gridFadeStoryBoard;
public ToastPopup(string Message)
{
InitializeComponent();
Label1.Content = DateTime.Now.ToString();
gridFadeStoryBoard = this.Label1.Template.Resources["gridFadeStoryBoard"] as Storyboard;
gridFadeStoryBoard.Completed += new EventHandler(gridFadeStoryBoard_Completed);
}
void gridFadeStoryBoard_Completed(object sender, EventArgs e)
{
this.Close();
}