<Window ......
xmlns:local="clr-namespace:WpfApp2"
xmlns:sys="clr-namespace:System;assembly=System.Runtime"
......>
<Window.Triggers>
<EventTrigger RoutedEvent="Window.Loaded">
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames Duration="0:0:2" RepeatBehavior="Forever" Storyboard.TargetName="sp_time" Storyboard.TargetProperty="DataContext">
<DiscreteObjectKeyFrame Value="{x:Static sys:DateTime.Now}" KeyTime="0:0:1"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Window.Triggers>
<Grid>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" DataContext="{x:Static sys:DateTime.Now}" Name="sp_time">
<TextBlock Text="{Binding Now,StringFormat=yyyy年MM月dd日 HH:mm:ss}" FontSize="18"/>
<TextBlock Text="{Binding Now,StringFormat=dddd,ConverterCulture=Zh}" FontSize="18" HorizontalAlignment="Center"/>
</StackPanel>
</Grid>
</Window>
有一点需要注意的是,仔细查看上面的代码,在TextBox
的Text
属性中进行绑定时,直接绑定了Now
属性,但是在给StackPanel
设置DataContext
时,并没有设置名为Now
的属性,只是设置了DateTime.Now
,但是WPF仍能自动绑定上。