1- namespace Client . Avalonia . ViewModels ;
1+ using System ;
2+ using System . ComponentModel ;
3+ using Avalonia . Threading ;
4+ using CommunityToolkit . Mvvm . ComponentModel ;
5+
6+ namespace Client . Avalonia . ViewModels ;
27
38public partial class MainWindowViewModel : ViewModelBase
49{
5- public string Greeting { get ; } = "Welcome to Avalonia!" ;
10+ [ ObservableProperty ] private DownloadStatistics _statistics ;
11+ [ ObservableProperty ] private bool _isCompleted ;
12+ private readonly DispatcherTimer _timer ;
13+
14+ public MainWindowViewModel ( )
15+ {
16+ Statistics = new DownloadStatistics
17+ {
18+ Version = "1.0.0" ,
19+ Speed = "1MB/s" ,
20+ Remaining = TimeSpan . Zero ,
21+ TotalBytesToReceive = 1024 * 1024 * 10 ,
22+ BytesReceived = 1024 * 1024 * 0 ,
23+ ProgressPercentage = 0
24+ } ;
25+
26+ _timer = new DispatcherTimer
27+ {
28+ Interval = TimeSpan . FromMilliseconds ( 1000 )
29+ } ;
30+ _timer . Tick += UpdateProgress ;
31+ _timer . Start ( ) ;
32+ }
33+
34+ private void UpdateProgress ( object ? sender , EventArgs e )
35+ {
36+ if ( Statistics . BytesReceived < Statistics . TotalBytesToReceive )
37+ {
38+ Statistics . BytesReceived += 1024 * 1024 ;
39+ Statistics . ProgressPercentage =
40+ ( double ) Statistics . BytesReceived / Statistics . TotalBytesToReceive * 100 ;
41+
42+ Statistics . Remaining = TimeSpan . FromSeconds (
43+ ( Statistics . TotalBytesToReceive - Statistics . BytesReceived ) / ( 1024 * 1024 ) ) ;
44+
45+ OnPropertyChanged ( nameof ( Statistics ) ) ;
46+
47+ if ( Statistics . BytesReceived >= Statistics . TotalBytesToReceive )
48+ {
49+ _timer . Stop ( ) ;
50+ IsCompleted = true ;
51+ }
52+ }
53+ }
54+ }
55+
56+ public partial class DownloadStatistics : ObservableObject
57+ {
58+ [ ObservableProperty ] [ Description ( "当前下载版本" ) ]
59+ private object ? _version ;
60+
61+ [ ObservableProperty ] [ Description ( "下载速度" ) ]
62+ private string ? _speed ;
63+
64+ [ ObservableProperty ] [ Description ( "剩余下载时间" ) ]
65+ private TimeSpan _remaining ;
66+
67+ [ ObservableProperty ] [ Description ( "已下载大小" ) ]
68+ private long _totalBytesToReceive ;
69+
70+ [ ObservableProperty ] [ Description ( "总大小" ) ]
71+ private long _bytesReceived ;
72+
73+ [ ObservableProperty ] [ Description ( "进度百分比" ) ]
74+ private double _progressPercentage ;
675}
0 commit comments