-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUsageMeter.cs
More file actions
98 lines (82 loc) · 2.79 KB
/
UsageMeter.cs
File metadata and controls
98 lines (82 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Shapes;
using System;
namespace CodexBarWin;
public sealed class UsageMeter : Grid
{
public static readonly DependencyProperty UsedPercentProperty = DependencyProperty.Register(
nameof(UsedPercent),
typeof(double),
typeof(UsageMeter),
new PropertyMetadata(0d, OnMeterPropertyChanged));
public static readonly DependencyProperty FillBrushProperty = DependencyProperty.Register(
nameof(FillBrush),
typeof(Brush),
typeof(UsageMeter),
new PropertyMetadata(null, OnMeterPropertyChanged));
public static readonly DependencyProperty TrackBrushProperty = DependencyProperty.Register(
nameof(TrackBrush),
typeof(Brush),
typeof(UsageMeter),
new PropertyMetadata(null, OnMeterPropertyChanged));
private readonly Rectangle _track;
private readonly Rectangle _fill;
public UsageMeter()
{
MinHeight = 6;
Height = 6;
HorizontalAlignment = HorizontalAlignment.Stretch;
_track = new Rectangle
{
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch
};
_fill = new Rectangle
{
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Stretch
};
Children.Add(_track);
Children.Add(_fill);
SizeChanged += (_, _) => UpdateMeter();
Loaded += (_, _) => UpdateMeter();
}
public double UsedPercent
{
get => (double)GetValue(UsedPercentProperty);
set => SetValue(UsedPercentProperty, value);
}
public Brush? FillBrush
{
get => (Brush?)GetValue(FillBrushProperty);
set => SetValue(FillBrushProperty, value);
}
public Brush? TrackBrush
{
get => (Brush?)GetValue(TrackBrushProperty);
set => SetValue(TrackBrushProperty, value);
}
private static void OnMeterPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
{
if (dependencyObject is UsageMeter meter)
{
meter.UpdateMeter();
}
}
private void UpdateMeter()
{
var height = ActualHeight > 0 ? ActualHeight : Height;
var width = ActualWidth > 0 ? ActualWidth : Width;
var radius = Math.Max(0, height / 2);
var clamped = double.IsFinite(UsedPercent) ? Math.Clamp(UsedPercent, 0, 100) : 0;
_track.Fill = TrackBrush;
_track.RadiusX = radius;
_track.RadiusY = radius;
_fill.Fill = FillBrush;
_fill.RadiusX = radius;
_fill.RadiusY = radius;
_fill.Width = Math.Max(0, width * clamped / 100);
}
}