以下代碼使用Timer從 1 開始計數到永遠。
XAML 代碼:
<Window x:Class="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">
<Grid>
<Label x:Name="myLabel"/>
</Grid>
</Window>
vb.net 代碼:
Class MainWindow
Dim myDispatcherTimer As New Windows.Threading.DispatcherTimer With {.Interval = TimeSpan.FromSeconds(1)}
Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
AddHandler myDispatcherTimer.Tick, AddressOf Me.Hello
myDispatcherTimer.Start()
End Sub
Public Sub Hello()
Static myStatic As Integer = 0
myStatic = myStatic 1
myLabel.Content = myStatic
End Sub
End Class
我想通過使用Double Animation而不是使用Timer來計數。
可能嗎?
提前致謝。
uj5u.com熱心網友回復:
您可以創建一個附加型別的屬性,double該Content屬性設定應用它的任何 ContentControl(例如標簽)的屬性。
public static class Counter
{
public static readonly DependencyProperty CountProperty =
DependencyProperty.RegisterAttached(
"Count", typeof(double), typeof(Counter),
new PropertyMetadata(0d, CountPropertyChanged));
public static double GetCount(DependencyObject obj)
{
return (double)obj.GetValue(CountProperty);
}
public static void SetCount(DependencyObject obj, double value)
{
obj.SetValue(CountProperty, value);
}
private static void CountPropertyChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
if (obj is ContentControl control)
{
control.Content = string.Format("{0:F0}", args.NewValue);
}
}
}
然后通過適當的 DoubleAnimation 為該屬性設定影片。
<Label>
<Label.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(local:Counter.Count)"
From="0" By="1" Duration="0:0:1"
IsCumulative="True" RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Label.Triggers>
</Label>
由于您顯然只想顯示整數值,因此您不妨使用Int32Animation帶有 type 附加屬性的 an int。
public static class Counter
{
public static readonly DependencyProperty CountProperty =
DependencyProperty.RegisterAttached(
"Count", typeof(int), typeof(Counter),
new PropertyMetadata(0, CountPropertyChanged));
public static int GetCount(DependencyObject obj)
{
return (int)obj.GetValue(CountProperty);
}
public static void SetCount(DependencyObject obj, int value)
{
obj.SetValue(CountProperty, value);
}
private static void CountPropertyChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
if (obj is ContentControl control)
{
control.Content = args.NewValue;
}
}
}
和
<Storyboard>
<Int32Animation
Storyboard.TargetProperty="(local:Counter.Count)"
From="0" By="1" Duration="0:0:1"
IsCumulative="True" RepeatBehavior="Forever"/>
</Storyboard>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/503728.html
