Files
LanMountainDesktop/LanMontainDesktop/Views/Components/ClockWidget.axaml.cs

83 lines
2.1 KiB
C#
Raw Normal View History

2026-02-27 13:43:27 +08:00
using System;
using System.Globalization;
using Avalonia;
using Avalonia.Controls;
2026-02-27 15:15:09 +08:00
using Avalonia.Media;
2026-02-27 13:43:27 +08:00
using Avalonia.Threading;
2026-03-01 16:50:06 +08:00
using LanMontainDesktop.Services;
2026-02-27 13:43:27 +08:00
namespace LanMontainDesktop.Views.Components;
public partial class ClockWidget : UserControl
{
private readonly DispatcherTimer _timer = new()
{
Interval = TimeSpan.FromSeconds(1)
};
2026-03-01 16:50:06 +08:00
private TimeZoneService? _timeZoneService;
2026-02-27 13:43:27 +08:00
public ClockWidget()
{
InitializeComponent();
_timer.Tick += OnTimerTick;
AttachedToVisualTree += OnAttachedToVisualTree;
DetachedFromVisualTree += OnDetachedFromVisualTree;
UpdateClock();
}
2026-03-01 16:50:06 +08:00
/// <summary>
/// 设置时区服务
/// </summary>
public void SetTimeZoneService(TimeZoneService timeZoneService)
{
if (_timeZoneService != null)
{
_timeZoneService.TimeZoneChanged -= OnTimeZoneChanged;
}
_timeZoneService = timeZoneService;
_timeZoneService.TimeZoneChanged += OnTimeZoneChanged;
UpdateClock();
}
2026-02-27 13:43:27 +08:00
private void OnAttachedToVisualTree(object? sender, VisualTreeAttachmentEventArgs e)
{
UpdateClock();
_timer.Start();
}
private void OnDetachedFromVisualTree(object? sender, VisualTreeAttachmentEventArgs e)
{
_timer.Stop();
}
private void OnTimerTick(object? sender, EventArgs e)
{
UpdateClock();
}
2026-03-01 16:50:06 +08:00
private void OnTimeZoneChanged(object? sender, EventArgs e)
{
UpdateClock();
}
2026-02-27 13:43:27 +08:00
private void UpdateClock()
{
2026-03-01 16:50:06 +08:00
var now = _timeZoneService?.GetCurrentTime() ?? DateTime.Now;
2026-02-27 13:43:27 +08:00
TimeTextBlock.Text = now.ToString("HH:mm:ss", CultureInfo.CurrentCulture);
}
2026-02-27 15:15:09 +08:00
public void ApplyCellSize(double cellSize)
{
var padding = Math.Clamp(cellSize * 0.12, 2, 14);
RootBorder.Padding = new Thickness(padding);
RootBorder.CornerRadius = new CornerRadius(Math.Clamp(cellSize * 0.16, 4, 18));
// Keep the time legible across dense and sparse grid layouts.
TimeTextBlock.FontSize = Math.Clamp(cellSize * 0.42, 10, 56);
TimeTextBlock.FontWeight = FontWeight.SemiBold;
}
2026-02-27 13:43:27 +08:00
}