master
cs 74 lines 2.33 KB
Raw
1 // Copyright (C) Microsoft Corporation. All rights reserved.
2
3 using CommunityToolkit.Mvvm.ComponentModel;
4 using Microsoft.UI.Dispatching;
5 using System.Runtime.CompilerServices;
6 using System.Text.RegularExpressions;
7 using WslSettings.Contracts.Services;
8
9 namespace WslSettings.ViewModels.Settings
10 {
11 abstract public partial class WslConfigSettingViewModel : ObservableRecipient
12 {
13 private readonly DispatcherQueue _dispatcherQueue = DispatcherQueue.GetForCurrentThread();
14
15 protected WslConfigSettingViewModel()
16 {
17 App.GetService<IWslConfigService>().WslConfigChanged += OnConfigChanged;
18 }
19
20 public void OnConfigChanged()
21 {
22 InitializeConfigSettings();
23 _dispatcherQueue.TryEnqueue(() =>
24 {
25 OnPropertyChanged(String.Empty);
26 });
27 }
28
29 abstract protected void InitializeConfigSettings();
30
31 protected bool ValidateInput(string? newValue, Regex regex, [CallerMemberName] string? propertyName = null)
32 {
33 if (newValue == null || !regex.IsMatch(newValue))
34 {
35 // Notify the property so it can revert back to its previous value.
36 OnPropertyChanged(propertyName);
37 return false;
38 }
39
40 return true;
41 }
42
43 protected void Set<T>(ref IWslConfigSetting wslConfigSetting, T newValue, [CallerMemberName] string? propertyName = null)
44 {
45 if (wslConfigSetting.Equals(newValue))
46 {
47 return;
48 }
49
50 if (wslConfigSetting.SetValue(newValue) != 0)
51 {
52 SettingsContentVisibility = false;
53 ErrorVisibility = !SettingsContentVisibility;
54 return;
55 }
56
57 OnPropertyChanged(propertyName);
58 }
59
60 private bool _errorVisibility = false;
61 public bool ErrorVisibility
62 {
63 get => _errorVisibility;
64 set => SetProperty(ref _errorVisibility, value);
65 }
66
67 private bool _settingsContentVisibility = true;
68 public bool SettingsContentVisibility
69 {
70 get => _settingsContentVisibility;
71 set => SetProperty(ref _settingsContentVisibility, value);
72 }
73 }
74 }