color-picker/ViewModels/ColorPicker.cs
2023-03-08 14:13:08 +01:00

40 lines
1.3 KiB
C#

using CommunityToolkit.Mvvm.ComponentModel;
using System.Text.RegularExpressions;
namespace ColorPicker.ViewModels;
public partial class ColorPickerViewModel : ObservableObject {
[ObservableProperty]
private byte red = 0, green = 0, blue = 0;
[ObservableProperty]
private string color = "#000000", hexInput = "#000000";
public ColorPickerViewModel() {
calculateColorFromRgb();
}
partial void OnRedChanged(byte value) => calculateColorFromRgb();
partial void OnGreenChanged(byte value) => calculateColorFromRgb();
partial void OnBlueChanged(byte value) => calculateColorFromRgb();
partial void OnHexInputChanged(string value) {
if (!Regex.IsMatch(value, @"^#[\dA-F]{6}$", RegexOptions.IgnoreCase))
return;
this.Color = HexInput;
calculateRgbFromColor();
}
private void calculateRgbFromColor() {
var parse = (int start, int length) => byte.Parse(this.Color.Substring(start, length), System.Globalization.NumberStyles.HexNumber);
(this.Red, this.Green, this.Blue) = (parse(1, 2), parse(3, 2), parse(5, 2));
}
private void calculateColorFromRgb() {
this.Color = $"#{this.Red:X2}{this.Green:X2}{this.Blue:X2}";
this.HexInput = this.Color;
}
}