浏览代码

Add special regex tokenized formatter

Fresh installs get the new format, while existing ones will remain compatible and continue to use the old formatter.

Unfortunately the OutlinedTextBlock doesn't support multiline so #5 is not implemented with this alone.

Closes #8
Daniel Chalmers 2 年之前
父节点
当前提交
c6d45d089e
共有 2 个文件被更改,包括 27 次插入5 次删除
  1. 26 4
      DesktopClock/MainWindow.xaml.cs
  2. 1 1
      DesktopClock/Properties/Settings.cs

+ 26 - 4
DesktopClock/MainWindow.xaml.cs

@@ -2,6 +2,7 @@
 using System.ComponentModel;
 using System.Diagnostics;
 using System.IO;
+using System.Text.RegularExpressions;
 using System.Windows;
 using System.Windows.Controls;
 using System.Windows.Input;
@@ -20,6 +21,7 @@ namespace DesktopClock;
 [ObservableObject]
 public partial class MainWindow : Window
 {
+    private readonly Regex _tokenizerRegex = new("{([^{}]+)}", RegexOptions.Compiled);
     private readonly SystemClockTimer _systemClockTimer;
     private TaskbarIcon _trayIcon;
     private TimeZoneInfo _timeZone;
@@ -55,10 +57,30 @@ public partial class MainWindow : Window
     /// <summary>
     /// The current date and time in the selected time zone or countdown as a formatted string.
     /// </summary>
-    public string CurrentTimeOrCountdownString =>
-        IsCountdown ?
-        Settings.Default.CountdownTo.Humanize(CurrentTimeInSelectedTimeZone) :
-        CurrentTimeInSelectedTimeZone.ToString(Settings.Default.Format);
+    public string CurrentTimeOrCountdownString
+    {
+        get
+        {
+            if (IsCountdown)
+            {
+                return Settings.Default.CountdownTo.Humanize(CurrentTimeInSelectedTimeZone);
+            }
+            else
+            {
+                if (Settings.Default.Format.Contains("}"))
+                {
+                    // Use the datetime formatter on every string between { and } and leave the rest alone.
+                    return _tokenizerRegex.Replace(Settings.Default.Format, (m) =>
+                    {
+                        return CurrentTimeInSelectedTimeZone.ToString(m.Value);
+                    }).Replace("{", "").Replace("}", "");
+                }
+
+                // Use basic formatter if no special formatting tokens are present.
+                return CurrentTimeInSelectedTimeZone.ToString(Settings.Default.Format);
+            }
+        }
+    }
 
     [RelayCommand]
     public void CopyToClipboard() =>

+ 1 - 1
DesktopClock/Properties/Settings.cs

@@ -49,7 +49,7 @@ public sealed class Settings : INotifyPropertyChanged, IDisposable
     #region "Properties"
 
     public DateTimeOffset CountdownTo { get; set; } = DateTimeOffset.MinValue;
-    public string Format { get; set; } = "dddd, MMM dd, HH:mm:ss";
+    public string Format { get; set; } = "{dddd}, {MMM dd}, {HH:mm:ss}";
     public string TimeZone { get; set; } = string.Empty;
     public string FontFamily { get; set; } = "Consolas";
     public Color TextColor { get; set; }