Skip to content

Portable Tool for an Ideal Windows Setup

fix handle null values properly

Greedeksff03f5de2e44
diff --git a/.Source/GTweak/Assets/UserControls/Card.xaml.cs b/.Source/GTweak/Assets/UserControls/Card.xaml.cs
index 20317d57..3f8e8921 100644
--- a/.Source/GTweak/Assets/UserControls/Card.xaml.cs
+++ b/.Source/GTweak/Assets/UserControls/Card.xaml.cs
@@ -3,31 +3,35 @@ using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
-
namespace GTweak.Assets.UserControls
{
public partial class Card
{
- internal event EventHandler ClickButton;
- internal event EventHandler ClickButtonSecondary;
+ internal event EventHandler ClickButton, ClickButtonSecondary;
internal Style IconStyle { get => (Style)GetValue(IconStyleProperty); set => SetValue(IconStyleProperty, value); }
- internal DynamicResourceExtension Title { set => CardTitle.SetResourceReference(TextBlock.TextProperty, new DynamicResourceExtensionConverter().ConvertToString(value.ResourceKey)); }
- internal DynamicResourceExtension Description { set => CardText.SetResourceReference(TextBlock.TextProperty, new DynamicResourceExtensionConverter().ConvertToString(value.ResourceKey)); }
- internal DynamicResourceExtension BtnContent { set => CardButton.SetResourceReference(ContentProperty, new DynamicResourceExtensionConverter().ConvertToString(value.ResourceKey)); }
+
+ internal DynamicResourceExtension Title { set { if (value != null) { CardTitle?.SetResourceReference(TextBlock.TextProperty, new DynamicResourceExtensionConverter().ConvertToString(value.ResourceKey)); } } }
+
+ internal DynamicResourceExtension Description { set { if (value != null) { CardText?.SetResourceReference(TextBlock.TextProperty, new DynamicResourceExtensionConverter().ConvertToString(value.ResourceKey)); } } }
+
+ internal DynamicResourceExtension BtnContent { set { if (value != null) { CardButton?.SetResourceReference(ContentProperty, new DynamicResourceExtensionConverter().ConvertToString(value.ResourceKey)); } } }
internal DynamicResourceExtension BtnContentSecondary
{
set
{
- if (value != null)
- {
- CardButtonSecondary.SetResourceReference(ContentProperty, new DynamicResourceExtensionConverter().ConvertToString(value.ResourceKey));
- CardButtonSecondary.Visibility = Visibility.Visible;
- }
- else
+ if (CardButtonSecondary != null)
{
- CardButtonSecondary.Visibility = Visibility.Collapsed;
+ if (value != null)
+ {
+ CardButtonSecondary.SetResourceReference(ContentProperty, new DynamicResourceExtensionConverter().ConvertToString(value.ResourceKey));
+ CardButtonSecondary.Visibility = Visibility.Visible;
+ }
+ else
+ {
+ CardButtonSecondary.Visibility = Visibility.Collapsed;
+ }
}
}
}
@@ -39,13 +43,13 @@ namespace GTweak.Assets.UserControls
DependencyProperty.Register(nameof(TextBlock), typeof(string), typeof(Card), new PropertyMetadata(string.Empty));
internal static new readonly DependencyProperty ContentProperty =
- DependencyProperty.Register(nameof(BtnContent), typeof(string), typeof(Button), new PropertyMetadata(string.Empty, (s, e) => ((Button)s).Content = (string)e.NewValue));
+ DependencyProperty.Register(nameof(BtnContent), typeof(string), typeof(Button), new PropertyMetadata(string.Empty, (s, e) => { if (s is Button btn && e.NewValue is string str) { btn.Content = str; } }));
private static void OnIconStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is Card card && card.CardIcon != null)
{
- if (e.NewValue is Style style && style != null)
+ if (e.NewValue is Style style)
{
card.CardIcon.Style = style;
}
@@ -61,4 +65,4 @@ namespace GTweak.Assets.UserControls
private void CardButtonSecondary_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) => ClickButtonSecondary?.Invoke(this, EventArgs.Empty);
}
-}
+}
\ No newline at end of file
diff --git a/.Source/GTweak/Assets/UserControls/ColorPicker.xaml.cs b/.Source/GTweak/Assets/UserControls/ColorPicker.xaml.cs
index 9f3bd143..3a7cb167 100644
--- a/.Source/GTweak/Assets/UserControls/ColorPicker.xaml.cs
+++ b/.Source/GTweak/Assets/UserControls/ColorPicker.xaml.cs
@@ -32,9 +32,8 @@ namespace GTweak.Assets.UserControls
set => SetValue(DefaultColorProperty, value);
}
- internal static readonly DependencyProperty SelectedColorStringProperty =
- DependencyProperty.Register(nameof(SelectedColorString), typeof(string), typeof(ColorPicker),
- new FrameworkPropertyMetadata(default(string), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedColorStringChanged));
+ internal static readonly DependencyProperty SelectedColorStringProperty =
+ DependencyProperty.Register(nameof(SelectedColorString), typeof(string), typeof(ColorPicker), new FrameworkPropertyMetadata(default(string), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedColorStringChanged));
internal string SelectedColorString
{
@@ -67,42 +66,43 @@ namespace GTweak.Assets.UserControls
if (parentWindow != null)
{
- parentWindow.LocationChanged += delegate { UpdatePopupPosition(); };
- parentWindow.SizeChanged += delegate { UpdatePopupPosition(); };
+ parentWindow.LocationChanged += (s, args) => UpdatePopupPosition();
+ parentWindow.SizeChanged += (s, args) => UpdatePopupPosition();
}
}
private static void OnSelectedColorChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs)
{
- ColorPicker colorPickerControl = (ColorPicker)dependencyObject;
-
- if (!colorPickerControl._isUpdatingFromProperty)
+ if (dependencyObject is ColorPicker colorPickerControl && eventArgs.NewValue is Color newColor)
{
- colorPickerControl.UpdateInternalStateFromColor((Color)eventArgs.NewValue);
+ if (!colorPickerControl._isUpdatingFromProperty)
+ {
+ colorPickerControl.UpdateInternalStateFromColor(newColor);
+ }
}
}
private static void OnSelectedColorStringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
- ColorPicker picker = (ColorPicker)d;
- string newValue = e.NewValue as string;
-
- if (!string.IsNullOrWhiteSpace(newValue) && !picker._isUpdatingFromProperty)
+ if (d is ColorPicker picker && e.NewValue is string newValue)
{
- try
+ if (!string.IsNullOrWhiteSpace(newValue) && !picker._isUpdatingFromProperty)
{
- string[] components = newValue.Split(new[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
- if (components.Length == 3)
+ try
{
- Color newColor = Color.FromRgb(byte.Parse(components[0]), byte.Parse(components[1]), byte.Parse(components[2]));
-
- picker._isUpdatingFromProperty = true;
- picker.SelectedColor = newColor;
- picker.UpdateInternalStateFromColor(newColor);
- picker._isUpdatingFromProperty = false;
+ string[] components = newValue.Split(new[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
+ if (components.Length == 3)
+ {
+ Color newColor = Color.FromRgb(byte.Parse(components[0]), byte.Parse(components[1]), byte.Parse(components[2]));
+
+ picker._isUpdatingFromProperty = true;
+ picker.SelectedColor = newColor;
+ picker.UpdateInternalStateFromColor(newColor);
+ picker._isUpdatingFromProperty = false;
+ }
}
+ catch (Exception ex) { ErrorLogging.LogDebug(ex); }
}
- catch (Exception ex) { ErrorLogging.LogDebug(ex); }
}
}
@@ -115,46 +115,65 @@ namespace GTweak.Assets.UserControls
ColorPicked?.Invoke(this, EventArgs.Empty);
}
- private void PART_ToggleButton_Checked(object sender, RoutedEventArgs e) => ColorPopup.IsOpen = true;
+ private void PART_ToggleButton_Checked(object sender, RoutedEventArgs e)
+ {
+ if (ColorPopup != null)
+ {
+ ColorPopup.IsOpen = true;
+ }
+ }
- private void PART_ToggleButton_Unchecked(object sender, RoutedEventArgs e) => ColorPopup.IsOpen = false;
+ private void PART_ToggleButton_Unchecked(object sender, RoutedEventArgs e)
+ {
+ if (ColorPopup != null)
+ {
+ ColorPopup.IsOpen = false;
+ }
+ }
private void ColorPopup_Opened(object sender, EventArgs e)
{
_colorOnOpen = SelectedColor;
- PopupTransform.BeginAnimation(TranslateTransform.YProperty, FactoryAnimation.CreateIn(-5, 0, 0.3, useCubicEase: true));
- PopupBorder.BeginAnimation(UIElement.OpacityProperty, FactoryAnimation.CreateIn(0, 1, 0.15));
+ PopupTransform?.BeginAnimation(TranslateTransform.YProperty, FactoryAnimation.CreateIn(-5, 0, 0.3, useCubicEase: true));
+ PopupBorder?.BeginAnimation(UIElement.OpacityProperty, FactoryAnimation.CreateIn(0, 1, 0.15));
}
private void ColorPopup_Closed(object sender, EventArgs e)
{
- if (Mouse.LeftButton != MouseButtonState.Pressed || !PART_ToggleButton.IsMouseOver)
+ if (PART_ToggleButton != null)
{
- PART_ToggleButton.IsChecked = false;
- if (_colorOnOpen != SelectedColor)
+ if (Mouse.LeftButton != MouseButtonState.Pressed || !PART_ToggleButton.IsMouseOver)
{
- PickerClosed?.Invoke(this, EventArgs.Empty);
+ PART_ToggleButton.IsChecked = false;
+ if (_colorOnOpen != SelectedColor)
+ {
+ PickerClosed?.Invoke(this, EventArgs.Empty);
+ }
}
}
}
private void BtnDefault_Click(object sender, RoutedEventArgs e)
{
- SelectedColor = DefaultColor;
- UpdateInternalStateFromColor(DefaultColor);
- NotifyColorChanged(DefaultColor);
+ Color def = DefaultColor;
+ SelectedColor = def;
+ UpdateInternalStateFromColor(def);
+ NotifyColorChanged(def);
}
private void ColorWheel_MouseDown(object sender, MouseButtonEventArgs e)
{
- _isWheelBeingDragged = true;
- PART_Wheel.CaptureMouse();
- CalculateAndSetColorFromWheelPosition(e.GetPosition(PART_Wheel));
+ if (PART_Wheel != null)
+ {
+ _isWheelBeingDragged = true;
+ PART_Wheel.CaptureMouse();
+ CalculateAndSetColorFromWheelPosition(e.GetPosition(PART_Wheel));
+ }
}
private void ColorWheel_MouseMove(object sender, MouseEventArgs e)
{
- if (_isWheelBeingDragged)
+ if (_isWheelBeingDragged && PART_Wheel != null)
{
CalculateAndSetColorFromWheelPosition(e.GetPosition(PART_Wheel));
}
@@ -163,19 +182,22 @@ namespace GTweak.Assets.UserControls
private void ColorWheel_MouseUp(object sender, MouseButtonEventArgs e)
{
_isWheelBeingDragged = false;
- PART_Wheel.ReleaseMouseCapture();
+ PART_Wheel?.ReleaseMouseCapture();
}
private void ValueCanvas_MouseDown(object sender, MouseButtonEventArgs e)
{
- _isValueBeingDragged = true;
- PART_ValueCanvas.CaptureMouse();
- CalculateAndSetValueFromMouseY(e.GetPosition(PART_ValueCanvas).Y);
+ if (PART_ValueCanvas != null)
+ {
+ _isValueBeingDragged = true;
+ PART_ValueCanvas.CaptureMouse();
+ CalculateAndSetValueFromMouseY(e.GetPosition(PART_ValueCanvas).Y);
+ }
}
private void ValueCanvas_MouseMove(object sender, MouseEventArgs e)
{
- if (_isValueBeingDragged)
+ if (_isValueBeingDragged && PART_ValueCanvas != null)
{
CalculateAndSetValueFromMouseY(e.GetPosition(PART_ValueCanvas).Y);
}
@@ -184,15 +206,15 @@ namespace GTweak.Assets.UserControls
private void ValueCanvas_MouseUp(object sender, MouseButtonEventArgs e)
{
_isValueBeingDragged = false;
- PART_ValueCanvas.ReleaseMouseCapture();
+ PART_ValueCanvas?.ReleaseMouseCapture();
}
private void HexBox_KeyDown(object sender, KeyEventArgs e)
{
- if (e.Key == Key.Enter)
+ if (e?.Key == Key.Enter)
{
ValidateAndApplyHexColor();
- PART_HexBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
+ PART_HexBox?.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
@@ -200,7 +222,7 @@ namespace GTweak.Assets.UserControls
private void HexBox_TextChanged(object sender, TextChangedEventArgs e)
{
- if (!_isUpdatingHexValue)
+ if (!_isUpdatingHexValue && PART_HexBox != null)
{
string rawHexInput = PART_HexBox.Text.Trim().Replace("#", "");
string cleanedHexInput = Regex.Replace(rawHexInput, "[^0-9a-fA-F]", "");
@@ -222,7 +244,7 @@ namespace GTweak.Assets.UserControls
private void UpdatePopupPosition()
{
- if (ColorPopup.IsOpen)
+ if (ColorPopup != null && ColorPopup.IsOpen)
{
MethodInfo updatePositionMethod = typeof(System.Windows.Controls.Primitives.Popup).GetMethod("UpdatePosition", BindingFlags.NonPublic | BindingFlags.Instance);
updatePositionMethod?.Invoke(ColorPopup, null);
@@ -246,29 +268,24 @@ namespace GTweak.Assets.UserControls
_currentSaturation = Math.Min(1.0, distanceFromCenter / WheelRadius);
double angleInDegrees = Math.Atan2(deltaY, deltaX) * 180.0 / Math.PI;
-
- if (angleInDegrees < 0)
- {
- _currentHue = angleInDegrees + 360.0;
- }
- else
- {
- _currentHue = angleInDegrees;
- }
+ _currentHue = angleInDegrees < 0 ? angleInDegrees + 360.0 : angleInDegrees;
ApplyCurrentHsvToInterface();
}
private void CalculateAndSetValueFromMouseY(double mouseYPosition)
{
- double barHeight = PART_ValueBar.Height;
- double markerHeight = PART_MarkerValue.Height;
- double clampedY = Math.Max(markerHeight / 2, Math.Min(barHeight - markerHeight / 2, mouseYPosition));
+ if (PART_ValueBar != null && PART_MarkerValue != null)
+ {
+ double barHeight = PART_ValueBar.Height;
+ double markerHeight = PART_MarkerValue.Height;
+ double clampedY = Math.Max(markerHeight / 2, Math.Min(barHeight - markerHeight / 2, mouseYPosition));
- Canvas.SetTop(PART_MarkerValue, clampedY - markerHeight / 2);
- _currentValue = 1.0 - ((clampedY - markerHeight / 2) / (barHeight - markerHeight));
+ Canvas.SetTop(PART_MarkerValue, clampedY - markerHeight / 2);
+ _currentValue = 1.0 - ((clampedY - markerHeight / 2) / (barHeight - markerHeight));
- ApplyCurrentHsvToInterface();
+ ApplyCurrentHsvToInterface();
+ }
}
private void ApplyCurrentHsvToInterface()
@@ -281,12 +298,9 @@ namespace GTweak.Assets.UserControls
PART_ColorPreview.Fill = new SolidColorBrush(newColor);
PART_ColorTextBlock.Text = $"{newColor.R} {newColor.G} {newColor.B}";
- if (!_isUpdatingHexValue)
- {
- _isUpdatingHexValue = true;
- PART_HexBox.Text = $"#{newColor.R:X2}{newColor.G:X2}{newColor.B:X2}";
- _isUpdatingHexValue = false;
- }
+ _isUpdatingHexValue = true;
+ PART_HexBox.Text = $"#{newColor.R:X2}{newColor.G:X2}{newColor.B:X2}";
+ _isUpdatingHexValue = false;
NotifyColorChanged(newColor);
UpdateBrightnessBarBackground();
@@ -306,59 +320,68 @@ namespace GTweak.Assets.UserControls
private void UpdateBrightnessBarBackground()
{
- Color pureHueColor = ConvertHsvToRgbColor(_currentHue, _currentSaturation, 1.0);
- PART_ValueBar.Fill = new LinearGradientBrush(pureHueColor, Colors.Black, new Point(0.5, 0), new Point(0.5, 1));
+ if (PART_ValueBar != null)
+ {
+ Color pureHueColor = ConvertHsvToRgbColor(_currentHue, _currentSaturation, 1.0);
+ PART_ValueBar.Fill = new LinearGradientBrush(pureHueColor, Colors.Black, new Point(0.5, 0), new Point(0.5, 1));
+ }
}
private void UpdateBrightnessMarkerPosition()
{
- double barHeight = PART_ValueBar.Height;
- double markerHeight = PART_MarkerValue.Height;
- double markerYPosition = (1.0 - _currentValue) * (barHeight - markerHeight) + markerHeight / 2;
+ if (PART_ValueBar != null && PART_MarkerValue != null)
+ {
+ double barHeight = PART_ValueBar.Height;
+ double markerHeight = PART_MarkerValue.Height;
+ double markerYPosition = (1.0 - _currentValue) * (barHeight - markerHeight) + markerHeight / 2;
- Canvas.SetTop(PART_MarkerValue, markerYPosition - markerHeight / 2);
- Canvas.SetLeft(PART_MarkerValue, (PART_ValueBar.Width - markerHeight) / 2);
+ Canvas.SetTop(PART_MarkerValue, markerYPosition - markerHeight / 2);
+ Canvas.SetLeft(PART_MarkerValue, (PART_ValueBar.Width - markerHeight) / 2);
+ }
}
private void ValidateAndApplyHexColor()
{
- if (!_isUpdatingHexValue)
+ if (_isUpdatingHexValue || PART_HexBox == null)
{
- string rawHexInput = Regex.Replace(PART_HexBox.Text.Trim().Replace("#", ""), "[^0-9a-fA-F]", "");
-
- if (rawHexInput.Length != 0)
- {
- if (rawHexInput.Length < 6)
- {
- char lastCharacter = rawHexInput[rawHexInput.Length - 1];
- rawHexInput = rawHexInput.PadRight(6, lastCharacter);
- }
+ return;
+ }
- try
- {
- Color parsedColor = Color.FromRgb(Convert.ToByte(rawHexInput.Substring(0, 2), 16), Convert.ToByte(rawHexInput.Substring(2, 2), 16), Convert.ToByte(rawHexInput.Substring(4, 2), 16));
+ string rawHexInput = Regex.Replace(PART_HexBox.Text.Trim().Replace("#", ""), "[^0-9a-fA-F]", "");
- _isUpdatingHexValue = true;
- UpdateInternalStateFromColor(parsedColor);
- PART_HexBox.Text = $"#{rawHexInput.ToUpper()}";
- _isUpdatingHexValue = false;
- NotifyColorChanged(parsedColor);
- }
- catch { RevertHexBoxToSelectedColor(); }
+ if (rawHexInput.Length != 0)
+ {
+ if (rawHexInput.Length < 6)
+ {
+ char lastCharacter = rawHexInput[rawHexInput.Length - 1];
+ rawHexInput = rawHexInput.PadRight(6, lastCharacter);
}
- else
+
+ try
{
- RevertHexBoxToSelectedColor();
- return;
+ Color parsedColor = Color.FromRgb(Convert.ToByte(rawHexInput.Substring(0, 2), 16), Convert.ToByte(rawHexInput.Substring(2, 2), 16), Convert.ToByte(rawHexInput.Substring(4, 2), 16));
+ _isUpdatingHexValue = true;
+ UpdateInternalStateFromColor(parsedColor);
+ PART_HexBox.Text = $"#{rawHexInput.ToUpper()}";
+ _isUpdatingHexValue = false;
+ NotifyColorChanged(parsedColor);
}
+ catch { RevertHexBoxToSelectedColor(); }
+ }
+ else
+ {
+ RevertHexBoxToSelectedColor();
}
}
private void RevertHexBoxToSelectedColor()
{
- _isUpdatingHexValue = true;
- PART_HexBox.Text = $"#{SelectedColor.R:X2}{SelectedColor.G:X2}{SelectedColor.B:X2}";
- _isUpdatingHexValue = false;
+ if (PART_HexBox != null)
+ {
+ _isUpdatingHexValue = true;
+ PART_HexBox.Text = $"#{SelectedColor.R:X2}{SelectedColor.G:X2}{SelectedColor.B:X2}";
+ _isUpdatingHexValue = false;
+ }
}
private static void ConvertRgbToHsv(Color rgbColor, out double hue, out double saturation, out double value)
diff --git a/.Source/GTweak/Assets/UserControls/DescriptionBlock.xaml b/.Source/GTweak/Assets/UserControls/DescriptionBlock.xaml
index 8b05ae69..a068d8a0 100644
--- a/.Source/GTweak/Assets/UserControls/DescriptionBlock.xaml
+++ b/.Source/GTweak/Assets/UserControls/DescriptionBlock.xaml
@@ -5,7 +5,7 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:GTweak.Assets.UserControls"
mc:Ignorable="d" IsTabStop="False" KeyboardNavigation.TabNavigation="None" SnapsToDevicePixels="True" UseLayoutRounding="True"
- d:DesignHeight="450" d:DesignWidth="800" Loaded="DescriptionBlock_Loaded">
+ d:DesignHeight="450" d:DesignWidth="800">
<Grid Margin="10">
<ScrollViewer x:Name="Scroller" Margin="6" VerticalScrollBarVisibility="Hidden" HorizontalScrollBarVisibility="Disabled" ClipToBounds="True">
<TextBlock x:Name="FunctionDescription" Style="{StaticResource Description}" Text="{Binding DefaultText, RelativeSource={RelativeSource AncestorType=local:DescriptionBlock}}" TextWrapping="Wrap" TextTrimming="CharacterEllipsis" MaxWidth="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
diff --git a/.Source/GTweak/Assets/UserControls/DescriptionBlock.xaml.cs b/.Source/GTweak/Assets/UserControls/DescriptionBlock.xaml.cs
index 0c07d2bd..83cecb69 100644
--- a/.Source/GTweak/Assets/UserControls/DescriptionBlock.xaml.cs
+++ b/.Source/GTweak/Assets/UserControls/DescriptionBlock.xaml.cs
@@ -14,8 +14,8 @@ namespace GTweak.Assets.UserControls
internal string DefaultText
{
- get { return (string)GetValue(DefaultTextProperty); }
- set { SetValue(DefaultTextProperty, value); }
+ get => (string)GetValue(DefaultTextProperty);
+ set => SetValue(DefaultTextProperty, value);
}
public static readonly DependencyProperty DefaultTextProperty =
@@ -23,19 +23,24 @@ namespace GTweak.Assets.UserControls
internal string Text
{
- get => FunctionDescription.Text;
+ get => FunctionDescription?.Text ?? string.Empty;
set
{
+ string safeValue = value ?? string.Empty;
+
_scrollCts?.Cancel();
- Scroller.BeginAnimation(ScrollViewerBehavior.VerticalOffsetProperty, null);
- Scroller.ScrollToVerticalOffset(0);
- Scroller.UpdateLayout();
- TypewriterAnimation.Create(value, FunctionDescription,
- value.Length <= 50 ? TimeSpan.FromMilliseconds(200) : value.Length <= 200 ? TimeSpan.FromMilliseconds(400) : TimeSpan.FromMilliseconds(550));
+ if (Scroller != null && FunctionDescription != null)
+ {
+ Scroller.BeginAnimation(ScrollViewerBehavior.VerticalOffsetProperty, null);
+ Scroller.ScrollToVerticalOffset(0);
+ Scroller.UpdateLayout();
+
+ TypewriterAnimation.Create(safeValue, FunctionDescription, safeValue.Length <= 50 ? TimeSpan.FromMilliseconds(200) : safeValue.Length <= 200 ? TimeSpan.FromMilliseconds(400) : TimeSpan.FromMilliseconds(550));
- _scrollCts = new CancellationTokenSource();
- _ = StartAutoScrollAsync(value, _scrollCts.Token);
+ _scrollCts = new CancellationTokenSource();
+ _ = StartAutoScrollAsync(safeValue, _scrollCts.Token);
+ }
}
}
@@ -43,46 +48,57 @@ namespace GTweak.Assets.UserControls
{
InitializeComponent();
- Loaded += delegate { TypewriterAnimation.Create(DefaultText, FunctionDescription, TimeSpan.FromMilliseconds(300)); };
+ Loaded += delegate
+ {
+ if (FunctionDescription != null)
+ {
+ TypewriterAnimation.Create(DefaultText, FunctionDescription, TimeSpan.FromMilliseconds(300));
+ }
+ };
+
Unloaded += delegate { _scrollCts?.Cancel(); };
App.LanguageChanged += delegate
{
_scrollCts?.Cancel();
- TypewriterAnimation.Create(DefaultText, FunctionDescription, TimeSpan.Zero);
+ if (FunctionDescription != null)
+ {
+ TypewriterAnimation.Create(DefaultText, FunctionDescription, TimeSpan.Zero);
+ }
};
}
- private void DescriptionBlock_Loaded(object sender, RoutedEventArgs e) => TypewriterAnimation.Create(DefaultText, FunctionDescription, TimeSpan.FromMilliseconds(300));
private async Task StartAutoScrollAsync(string text, CancellationToken token)
{
await Task.Delay(2000, token);
- if (text == DefaultText || token.IsCancellationRequested)
+ if (text != DefaultText && !token.IsCancellationRequested)
{
- return;
- }
+ await Dispatcher.InvokeAsync(() =>
+ {
+ if (FunctionDescription != null && Scroller != null)
+ {
+ FunctionDescription.UpdateLayout();
+ Scroller.UpdateLayout();
+ Scroller.ScrollToVerticalOffset(0);
+ }
+ });
+
+ if (Scroller != null && !token.IsCancellationRequested)
+ {
+ double maxOffset = Scroller.ScrollableHeight;
+ if (maxOffset > 0)
+ {
+ double durationSeconds = Math.Max(2.0, maxOffset / 20);
- await Dispatcher.InvokeAsync(() =>
- {
- FunctionDescription.UpdateLayout();
- Scroller.UpdateLayout();
- Scroller.ScrollToVerticalOffset(0);
- });
+ await Dispatcher.InvokeAsync(() => { Scroller?.BeginAnimation(ScrollViewerBehavior.VerticalOffsetProperty, FactoryAnimation.CreateIn(0, maxOffset, durationSeconds, useCubicEase: true)); });
- double maxOffset = Scroller.ScrollableHeight;
- if (maxOffset <= 0)
- {
- return;
+ try { await Task.Delay(TimeSpan.FromSeconds(durationSeconds), token); }
+ catch (Exception ex) { ErrorLogging.LogDebug(ex); }
+ }
+ }
}
-
- double durationSeconds = Math.Max(2.0, maxOffset / 20);
-
- await Dispatcher.InvokeAsync(() => { Scroller.BeginAnimation(ScrollViewerBehavior.VerticalOffsetProperty, FactoryAnimation.CreateIn(0, maxOffset, durationSeconds, useCubicEase: true)); });
-
- try { await Task.Delay(TimeSpan.FromSeconds(durationSeconds), token); }
- catch (Exception ex) { ErrorLogging.LogDebug(ex); }
}
private static class ScrollViewerBehavior
@@ -90,15 +106,15 @@ namespace GTweak.Assets.UserControls
internal static readonly DependencyProperty VerticalOffsetProperty =
DependencyProperty.RegisterAttached("VerticalOffset", typeof(double), typeof(ScrollViewerBehavior), new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnVerticalOffsetChanged));
- internal static double GetVerticalOffset(ScrollViewer viewer) => (double)viewer.GetValue(VerticalOffsetProperty);
+ internal static double GetVerticalOffset(ScrollViewer viewer) => (double)(viewer?.GetValue(VerticalOffsetProperty) ?? 0.0);
- internal static void SetVerticalOffset(ScrollViewer viewer, double value) => viewer.SetValue(VerticalOffsetProperty, value);
+ internal static void SetVerticalOffset(ScrollViewer viewer, double value) => viewer?.SetValue(VerticalOffsetProperty, value);
private static void OnVerticalOffsetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
- if (d is ScrollViewer viewer)
+ if (d is ScrollViewer viewer && e.NewValue is double offset)
{
- viewer.ScrollToVerticalOffset((double)e.NewValue);
+ viewer.ScrollToVerticalOffset(offset);
}
}
}
diff --git a/.Source/GTweak/Assets/UserControls/FlowPanel.cs b/.Source/GTweak/Assets/UserControls/FlowPanel.cs
index 562bf867..7f50f748 100644
--- a/.Source/GTweak/Assets/UserControls/FlowPanel.cs
+++ b/.Source/GTweak/Assets/UserControls/FlowPanel.cs
@@ -133,12 +133,12 @@ namespace GTweak.Assets.UserControls
}
}
- protected override Size MeasureOverride(Size availableSize)
+ private void UpdateVisibleCache()
{
- try
+ _visibleCache.Clear();
+ UIElementCollection children = InternalChildren;
+ if (children != null)
{
- _visibleCache.Clear();
- UIElementCollection children = InternalChildren;
for (int i = 0; i < children.Count; i++)
{
UIElement child = children[i];
@@ -147,6 +147,14 @@ namespace GTweak.Assets.UserControls
_visibleCache.Add(child);
}
}
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ try
+ {
+ UpdateVisibleCache();
if (_visibleCache.Count == 0)
{
@@ -160,7 +168,7 @@ namespace GTweak.Assets.UserControls
for (int i = 0; i < _visibleCache.Count; i++)
{
- _visibleCache[i].Measure(constraint);
+ _visibleCache[i]?.Measure(constraint);
}
if (_cachedLayout != null)
@@ -172,26 +180,7 @@ namespace GTweak.Assets.UserControls
_cachedMeasureWidth = aw;
_cachedLayout = CreateOptimalColumns(aw, ah, _visibleCache);
- double neededHeight = 0;
- if (_cachedLayout != null)
- {
- if (Orientation == FlowOrientation.Horizontal)
- {
- for (int i = 0; i < _cachedLayout.Count; i++)
- {
- neededHeight += _cachedLayout[i].Height;
- if (i > 0)
- {
- neededHeight += VerticalSpacing;
- }
- }
- }
- else
- {
- neededHeight = CalculateMaxColumnHeight(_cachedLayout);
- }
- }
-
+ double neededHeight = CalculateLayoutHeight(_cachedLayout);
return new Size(aw, neededHeight);
}
catch (Exception ex)
@@ -201,20 +190,37 @@ namespace GTweak.Assets.UserControls
}
}
- protected override Size ArrangeOverride(Size finalSize)
+ private double CalculateLayoutHeight(List<FlowItemGroup> layout)
{
- try
+ if (layout == null || layout.Count == 0)
{
- _visibleCache.Clear();
- UIElementCollection children = InternalChildren;
- for (int i = 0; i < children.Count; i++)
+ return 0;
+ }
+
+ double neededHeight = 0;
+ if (Orientation == FlowOrientation.Horizontal)
+ {
+ for (int i = 0; i < layout.Count; i++)
{
- UIElement child = children[i];
- if (child != null && child.Visibility != Visibility.Collapsed)
+ neededHeight += layout[i].Height;
+ if (i > 0)
{
- _visibleCache.Add(child);
+ neededHeight += VerticalSpacing;
}
}
+ }
+ else
+ {
+ neededHeight = CalculateMaxColumnHeight(layout);
+ }
+ return neededHeight;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ try
+ {
+ UpdateVisibleCache();
if (_visibleCache.Count != 0)
{
@@ -243,8 +249,6 @@ namespace GTweak.Assets.UserControls
ReleaseGroups(_cachedLayout);
_cachedLayout = null;
}
-
- return finalSize;
}
return finalSize;
@@ -260,71 +264,80 @@ namespace GTweak.Assets.UserControls
{
if (groups != null && groups.Count != 0)
{
- if (Orientation == FlowOrientation.Horizontal)
+ switch (Orientation)
{
- double y = 0;
- for (int i = 0; i < groups.Count; i++)
- {
- FlowItemGroup row = groups[i];
- if (row.Elements.Count == 0)
- {
- y += row.Height + VerticalSpacing;
- continue;
- }
-
- double extraSpace = Math.Max(0, availableWidth - row.Width);
- double xStart = ContentAlignment switch
- {
- HorizontalAlignment.Center => extraSpace / 2.0,
- HorizontalAlignment.Right => extraSpace,
- _ => 0
- };
-
- double x = xStart;
- foreach (UIElement child in row.Elements)
- {
- double w = GetChildWidth(child);
- double h = GetChildHeight(child);
-
- Point newPos = new Point(x, y);
- child.Arrange(new Rect(newPos.X, newPos.Y, w, h));
-
- x += w + HorizontalSpacing;
- }
+ case FlowOrientation.Horizontal:
+ ArrangeHorizontal(groups, availableWidth);
+ break;
+ default:
+ ArrangeVertical(groups, availableWidth);
+ break;
+ }
+ }
+ }
+ private void ArrangeHorizontal(List<FlowItemGroup> groups, double availableWidth)
+ {
+ double y = 0;
+ for (int i = 0; i < groups.Count; i++)
+ {
+ FlowItemGroup row = groups[i];
+ if (row == null || row.Elements.Count == 0)
+ {
+ if (row != null)
+ {
y += row.Height + VerticalSpacing;
}
- return;
+
+ continue;
}
- double contentWidth = CalculateTotalWidth(groups);
- double extraSpaceV = Math.Max(0, availableWidth - contentWidth);
- double xStartV = ContentAlignment switch
+ double extraSpace = Math.Max(0, availableWidth - row.Width);
+ double x = ContentAlignment switch
{
- HorizontalAlignment.Center => extraSpaceV / 2.0,
- HorizontalAlignment.Right => extraSpaceV,
+ HorizontalAlignment.Center => extraSpace / 2.0,
+ HorizontalAlignment.Right => extraSpace,
_ => 0
};
- double xV = xStartV;
- for (int i = 0; i < groups.Count; i++)
+ foreach (UIElement child in row.Elements)
{
- FlowItemGroup col = groups[i];
- if (col.Elements.Count == 0)
+ if (child != null)
{
- xV += col.Width + HorizontalSpacing;
- continue;
+ double w = GetChildWidth(child);
+ double h = GetChildHeight(child);
+
+ child.Arrange(new Rect(x, y, w, h));
+ x += w + HorizontalSpacing;
}
+ }
+
+ y += row.Height + VerticalSpacing;
+ }
+ }
+
+ private void ArrangeVertical(List<FlowItemGroup> groups, double availableWidth)
+ {
+ double contentWidth = CalculateTotalWidth(groups);
+ double extraSpaceV = Math.Max(0, availableWidth - contentWidth);
+ double xV = ContentAlignment switch
+ {
+ HorizontalAlignment.Center => extraSpaceV / 2.0,
+ HorizontalAlignment.Right => extraSpaceV,
+ _ => 0
+ };
+ for (int i = 0; i < groups.Count; i++)
+ {
+ FlowItemGroup col = groups[i];
+ if (col != null && col.Elements.Count != 0)
+ {
double shift = 0;
- if (Orientation == FlowOrientation.Unset && groups.Count > 1)
+ if (Orientation == FlowOrientation.Unset && groups.Count > 1 && i > 0)
{
- if (i > 0)
- {
- double maxShiftPerColumn = col.Width * 0.2;
- double shareOfSpace = extraSpaceV * ((double)i / (groups.Count - 1)) * 0.3;
- shift = Math.Min(shareOfSpace, maxShiftPerColumn);
- }
+ double maxShiftPerColumn = col.Width * 0.2;
+ double shareOfSpace = extraSpaceV * ((double)i / (groups.Count - 1)) * 0.3;
+ shift = Math.Min(shareOfSpace, maxShiftPerColumn);
}
double columnX = xV + shift;
@@ -332,55 +345,41 @@ namespace GTweak.Assets.UserControls
foreach (UIElement child in col.Elements)
{
- double w = GetChildWidth(child);
- double h = GetChildHeight(child);
-
- Point newPos = new Point(columnX, y);
- child.Arrange(new Rect(newPos.X, newPos.Y, w, h));
+ if (child != null)
+ {
+ double w = GetChildWidth(child);
+ double h = GetChildHeight(child);
- y += h + VerticalSpacing;
+ child.Arrange(new Rect(columnX, y, w, h));
+ y += h + VerticalSpacing;
+ }
}
xV += col.Width + HorizontalSpacing;
}
- }
- }
-
- private double CalculateNeededHeight(double availableWidth, double availableHeight, List<UIElement> visibleChildren)
- {
- List<FlowItemGroup> groups = CreateOptimalColumns(availableWidth, availableHeight, visibleChildren);
- if (groups != null)
- {
- double total = 0;
- if (Orientation == FlowOrientation.Horizontal)
+ else
{
- for (int i = 0; i < groups.Count; i++)
+ if (col != null)
{
- total += groups[i].Height;
- if (i > 0)
- {
- total += VerticalSpacing;
- }
+ xV += col.Width + HorizontalSpacing;
}
- }
- else
- {
- total = CalculateMaxColumnHeight(groups);
- }
- ReleaseGroups(groups);
- return total;
+ continue;
+ }
}
-
- return 0;
}
private double CalculateMaxColumnHeight(List<FlowItemGroup> columns)
{
+ if (columns == null || columns.Count == 0)
+ {
+ return 0;
+ }
+
double max = 0;
for (int i = 0; i < columns.Count; i++)
{
- if (columns[i].Height > max)
+ if (columns[i] != null && columns[i].Height > max)
{
max = columns[i].Height;
}
@@ -390,6 +389,11 @@ namespace GTweak.Assets.UserControls
private List<FlowItemGroup> CreateOptimalColumns(double availableWidth, double availableHeight, List<UIElement> visibleChildren)
{
+ if (visibleChildren == null || visibleChildren.Count == 0)
+ {
+ return GetGroupList();
+ }
+
switch (Orientation)
{
case FlowOrientation.Horizontal:
@@ -442,39 +446,47 @@ namespace GTweak.Assets.UserControls
private List<FlowItemGroup> CreateWrappedRows(double maxWidth, List<UIElement> visibleChildren)
{
List<FlowItemGroup> rows = GetGroupList();
+ if (visibleChildren == null)
+ {
+ return rows;
+ }
+
FlowItemGroup current = null;
for (int i = 0; i < visibleChildren.Count; i++)
{
UIElement child = visibleChildren[i];
- double childWidth = GetChildWidth(child);
- double childHeight = GetChildHeight(child);
-
- if (current == null)
+ if (child != null)
{
- current = GetGroup();
- current.Elements.Add(child);
- current.Width = childWidth;
- current.Height = childHeight;
- rows.Add(current);
- continue;
- }
+ double childWidth = GetChildWidth(child);
+ double childHeight = GetChildHeight(child);
- double widthIfAdded = current.Width + (current.Width > 0 ? HorizontalSpacing : 0) + childWidth;
+ if (current == null)
+ {
+ current = GetGroup();
+ current.Elements.Add(child);
+ current.Width = childWidth;
+ current.Height = childHeight;
+ rows.Add(current);
+ continue;
+ }
- if (widthIfAdded <= maxWidth || current.Elements.Count == 0)
- {
- current.Elements.Add(child);
- current.Width = widthIfAdded;
- current.Height = Math.Max(current.Height, childHeight);
- }
- else
- {
- current = GetGroup();
- current.Elements.Add(child);
- current.Width = childWidth;
- current.Height = childHeight;
- rows.Add(current);
+ double widthIfAdded = current.Width + (current.Width > 0 ? HorizontalSpacing : 0) + childWidth;
+
+ if (widthIfAdded <= maxWidth || current.Elements.Count == 0)
+ {
+ current.Elements.Add(child);
+ current.Width = widthIfAdded;
+ current.Height = Math.Max(current.Height, childHeight);
+ }
+ else
+ {
+ current = GetGroup();
+ current.Elements.Add(child);
+ current.Width = childWidth;
+ current.Height = childHeight;
+ rows.Add(current);
+ }
}
}
return rows;
@@ -483,39 +495,47 @@ namespace GTweak.Assets.UserControls
private List<FlowItemGroup> CreateWrappedColumns(double maxHeight, List<UIElement> visibleChildren)
{
List<FlowItemGroup> cols = GetGroupList();
+ if (visibleChildren == null)
+ {
+ return cols;
+ }
+
FlowItemGroup current = null;
for (int i = 0; i < visibleChildren.Count; i++)
{
UIElement child = visibleChildren[i];
- double childWidth = GetChildWidth(child);
- double childHeight = GetChildHeight(child);
-
- if (current == null)
+ if (child != null)
{
- current = GetGroup();
- current.Elements.Add(child);
- current.Width = childWidth;
- current.Height = childHeight;
- cols.Add(current);
- continue;
- }
+ double childWidth = GetChildWidth(child);
+ double childHeight = GetChildHeight(child);
+
+ if (current == null)
+ {
+ current = GetGroup();
+ current.Elements.Add(child);
+ current.Width = childWidth;
+ current.Height = childHeight;
+ cols.Add(current);
+ continue;
+ }
- double heightIfAdded = current.Height + (current.Height > 0 ? VerticalSpacing : 0) + childHeight;
+ double heightIfAdded = current.Height + (current.Height > 0 ? VerticalSpacing : 0) + childHeight;
- if (heightIfAdded <= maxHeight || current.Elements.Count == 0)
- {
- current.Elements.Add(child);
- current.Height = heightIfAdded;
- current.Width = Math.Max(current.Width, childWidth);
- }
- else
- {
- current = GetGroup();
- current.Elements.Add(child);
- current.Width = childWidth;
- current.Height = childHeight;
- cols.Add(current);
+ if (heightIfAdded <= maxHeight || current.Elements.Count == 0)
+ {
+ current.Elements.Add(child);
+ current.Height = heightIfAdded;
+ current.Width = Math.Max(current.Width, childWidth);
+ }
+ else
+ {
+ current = GetGroup();
+ current.Elements.Add(child);
+ current.Width = childWidth;
+ current.Height = childHeight;
+ cols.Add(current);
+ }
}
}
return cols;
@@ -529,6 +549,11 @@ namespace GTweak.Assets.UserControls
columns.Add(GetGroup());
}
+ if (visibleChildren == null)
+ {
+ return columns;
+ }
+
if (UseMasonryLayout)
{
if (_heightCache.Length < columnCount)
@@ -541,29 +566,32 @@ namespace GTweak.Assets.UserControls
for (int c = 0; c < visibleChildren.Count; c++)
{
UIElement child = visibleChildren[c];
- int minIndex = 0;
- double minH = _heightCache[0];
- for (int i = 1; i < columnCount; i++)
+ if (child != null)
{
- if (_heightCache[i] < minH)
+ int minIndex = 0;
+ double minH = _heightCache[0];
+ for (int i = 1; i < columnCount; i++)
{
- minH = _heightCache[i];
- minIndex = i;
+ if (_heightCache[i] < minH)
+ {
+ minH = _heightCache[i];
+ minIndex = i;
+ }
}
- }
- double h = GetChildHeight(child);
- double newHeight = _heightCache[minIndex] + (_heightCache[minIndex] > 0 ? VerticalSpacing : 0) + h;
+ double h = GetChildHeight(child);
+ double newHeight = _heightCache[minIndex] + (_heightCache[minIndex] > 0 ? VerticalSpacing : 0) + h;
- if (!double.IsInfinity(maxHeight) && newHeight > maxHeight)
- {
- ReleaseGroups(columns);
- return null;
- }
+ if (!double.IsInfinity(maxHeight) && newHeight > maxHeight)
+ {
+ ReleaseGroups(columns);
+ return null;
+ }
- columns[minIndex].Elements.Add(child);
- columns[minIndex].Width = Math.Max(columns[minIndex].Width, GetChildWidth(child));
- _heightCache[minIndex] = newHeight;
+ columns[minIndex].Elements.Add(child);
+ columns[minIndex].Width = Math.Max(columns[minIndex].Width, GetChildWidth(child));
+ _heightCache[minIndex] = newHeight;
+ }
}
for (int i = 0; i < columnCount; i++)
@@ -576,20 +604,23 @@ namespace GTweak.Assets.UserControls
for (int index = 0; index < visibleChildren.Count; index++)
{
UIElement child = visibleChildren[index];
- int colIndex = index % columnCount;
+ if (child != null)
+ {
+ int colIndex = index % columnCount;
- double addedHeight = (columns[colIndex].Height > 0 ? VerticalSpacing : 0) + GetChildHeight(child);
- double newHeight = columns[colIndex].Height + addedHeight;
+ double addedHeight = (columns[colIndex].Height > 0 ? VerticalSpacing : 0) + GetChildHeight(child);
+ double newHeight = columns[colIndex].Height + addedHeight;
- if (!double.IsInfinity(maxHeight) && newHeight > maxHeight)
- {
- ReleaseGroups(columns);
- return null;
- }
+ if (!double.IsInfinity(maxHeight) && newHeight > maxHeight)
+ {
+ ReleaseGroups(columns);
+ return null;
+ }
- columns[colIndex].Elements.Add(child);
- columns[colIndex].Width = Math.Max(columns[colIndex].Width, GetChildWidth(child));
- columns[colIndex].Height = newHeight;
+ columns[colIndex].Elements.Add(child);
+ columns[colIndex].Width = Math.Max(columns[colIndex].Width, GetChildWidth(child));
+ columns[colIndex].Height = newHeight;
+ }
}
}
@@ -602,16 +633,22 @@ namespace GTweak.Assets.UserControls
FlowItemGroup col = GetGroup();
double totalHeight = 0;
- for (int i = 0; i < visibleChildren.Count; i++)
+ if (visibleChildren != null)
{
- UIElement child = visibleChildren[i];
- col.Elements.Add(child);
- col.Width = Math.Max(col.Width, GetChildWidth(child));
- totalHeight += GetChildHeight(child);
-
- if (i > 0)
+ for (int i = 0; i < visibleChildren.Count; i++)
{
- totalHeight += VerticalSpacing;
+ UIElement child = visibleChildren[i];
+ if (child != null)
+ {
+ col.Elements.Add(child);
+ col.Width = Math.Max(col.Width, GetChildWidth(child));
+ totalHeight += GetChildHeight(child);
+
+ if (i > 0)
+ {
+ totalHeight += VerticalSpacing;
+ }
+ }
}
}
@@ -622,16 +659,24 @@ namespace GTweak.Assets.UserControls
private double CalculateTotalWidth(List<FlowItemGroup> columns)
{
- double total = 0;
- for (int i = 0; i < columns.Count; i++)
+ if (columns != null && columns.Count != 0)
{
- total += columns[i].Width;
- if (i > 0)
+ double total = 0;
+ for (int i = 0; i < columns.Count; i++)
{
- total += HorizontalSpacing;
+ if (columns[i] != null)
+ {
+ total += columns[i].Width;
+ if (i > 0)
+ {
+ total += HorizontalSpacing;
+ }
+ }
}
+ return total;
}
- return total;
+
+ return 0;
}
protected override void OnVisualChildrenChanged(DependencyObject visualAdded, DependencyObject visualRemoved)
diff --git a/.Source/GTweak/Assets/UserControls/ToggleButton.xaml.cs b/.Source/GTweak/Assets/UserControls/ToggleButton.xaml.cs
index 9635f97e..13f51904 100644
--- a/.Source/GTweak/Assets/UserControls/ToggleButton.xaml.cs
+++ b/.Source/GTweak/Assets/UserControls/ToggleButton.xaml.cs
@@ -64,12 +64,17 @@ namespace GTweak.Assets.UserControls
internal object TextResource
{
get => (string)GetValue(TextProperty);
- set => ApplyResource(value, TextProperty, TextBlock.TextProperty, ToggleText);
+ set
+ {
+ if (value != null)
+ {
+ ApplyResource(value, TextProperty, TextBlock.TextProperty, ToggleText);
+ }
+ }
}
private static readonly DependencyProperty TextProperty =
- DependencyProperty.Register(nameof(TextResource), typeof(string), typeof(ToggleButton), new PropertyMetadata("", (s, e) => ((ToggleButton)s).ToggleText.Text = (string)e.NewValue));
-
+ DependencyProperty.Register(nameof(TextResource), typeof(string), typeof(ToggleButton), new PropertyMetadata("", (s, e) => { if (s is ToggleButton btn && btn.ToggleText != null) { btn.ToggleText.Text = e.NewValue as string; } }));
/// <summary>
/// Sets the description text for the ToggleButton. Can be assigned from a DynamicResource, StaticResource, or directly as a string.
@@ -77,7 +82,13 @@ namespace GTweak.Assets.UserControls
internal object Description
{
get => GetValue(DescriptionProperty);
- set => ApplyResource(value, DescriptionProperty);
+ set
+ {
+ if (value != null)
+ {
+ ApplyResource(value, DescriptionProperty);
+ }
+ }
}
private static readonly DependencyProperty DescriptionProperty = DependencyProperty.Register(nameof(Description), typeof(object), typeof(ToggleButton), new PropertyMetadata(null));
@@ -99,28 +110,34 @@ namespace GTweak.Assets.UserControls
private void ApplyResource(object value, DependencyProperty dp, DependencyProperty textProperty = null, FrameworkElement target = null)
{
- if (dp != null || target != null)
+ if (value != null && (dp != null || target != null))
{
switch (value)
{
case DynamicResourceExtension dynamicResource:
- if (target != null && textProperty != null)
- {
- target.SetResourceReference(textProperty, dynamicResource.ResourceKey);
- }
- else if (dp != null)
+ if (dynamicResource.ResourceKey != null)
{
- SetResourceReference(dp, dynamicResource.ResourceKey);
+ if (target != null && textProperty != null)
+ {
+ target.SetResourceReference(textProperty, dynamicResource.ResourceKey);
+ }
+ else if (dp != null)
+ {
+ SetResourceReference(dp, dynamicResource.ResourceKey);
+ }
}
break;
case StaticResourceExtension staticResource:
- if (target != null && textProperty != null)
+ if (staticResource.ResourceKey != null)
{
- target.SetResourceReference(textProperty, staticResource.ResourceKey);
- }
- else if (dp != null)
- {
- SetResourceReference(dp, staticResource.ResourceKey);
+ if (target != null && textProperty != null)
+ {
+ target.SetResourceReference(textProperty, staticResource.ResourceKey);
+ }
+ else if (dp != null)
+ {
+ SetResourceReference(dp, staticResource.ResourceKey);
+ }
}
break;
default:
@@ -137,26 +154,28 @@ namespace GTweak.Assets.UserControls
}
}
-
private void ToggleButton_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
- if (e.NewValue is bool newBool && !newBool)
+ if (Back != null && Dot != null && ToggleText != null)
{
- Back.Opacity = 0.7;
- Dot.Opacity = 0.7;
- ToggleText.Opacity = 0.7;
- }
- else
- {
- Back.Opacity = 1.0;
- Dot.Opacity = 1.0;
- ToggleText.Opacity = 1.0;
+ if (e.NewValue is bool newBool && !newBool)
+ {
+ Back.Opacity = 0.7;
+ Dot.Opacity = 0.7;
+ ToggleText.Opacity = 0.7;
+ }
+ else
+ {
+ Back.Opacity = 1.0;
+ Dot.Opacity = 1.0;
+ ToggleText.Opacity = 1.0;
+ }
}
}
private void Toggle_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
- if (IsEnabled || sender.GetType() != typeof(TextBlock))
+ if (IsEnabled || sender?.GetType() != typeof(TextBlock))
{
RaiseEvent(new RoutedEventArgs(ChangedStateEvent));
State = !_state;
@@ -183,7 +202,7 @@ namespace GTweak.Assets.UserControls
EasingFunction = new QuadraticEase()
});
Timeline.SetDesiredFrameRate(marginAnimation, 120);
- Dot.BeginAnimation(MarginProperty, marginAnimation);
+ Dot?.BeginAnimation(MarginProperty, marginAnimation);
BrushAnimation brushAnimation = new BrushAnimation
{
@@ -192,7 +211,7 @@ namespace GTweak.Assets.UserControls
Duration = skipAnimation ? TimeSpan.Zero : TimeSpan.FromMilliseconds(100)
};
Timeline.SetDesiredFrameRate(brushAnimation, 120);
- Back.BeginAnimation(Shape.FillProperty, brushAnimation);
+ Back?.BeginAnimation(Shape.FillProperty, brushAnimation);
BrushAnimation borderAnimation = new BrushAnimation
{
@@ -201,8 +220,7 @@ namespace GTweak.Assets.UserControls
Duration = skipAnimation ? TimeSpan.Zero : TimeSpan.FromMilliseconds(100)
};
Timeline.SetDesiredFrameRate(borderAnimation, 120);
- Back.BeginAnimation(Shape.StrokeProperty, borderAnimation);
-
+ Back?.BeginAnimation(Shape.StrokeProperty, borderAnimation);
ColorAnimation dotColorAnimation = new ColorAnimation
{
@@ -211,14 +229,21 @@ namespace GTweak.Assets.UserControls
EasingFunction = new QuadraticEase()
};
Timeline.SetDesiredFrameRate(dotColorAnimation, 120);
- ((SolidColorBrush)Dot.Fill).BeginAnimation(SolidColorBrush.ColorProperty, dotColorAnimation);
- ToggleText.Style = (Style)FindResource(textStyle);
+ if (Dot?.Fill is SolidColorBrush solidColorBrush)
+ {
+ solidColorBrush.BeginAnimation(SolidColorBrush.ColorProperty, dotColorAnimation);
+ }
+
+ if (ToggleText != null && TryFindResource(textStyle) is Style foundStyle)
+ {
+ ToggleText.Style = foundStyle;
+ }
}
private void Toggle_MouseEnter(object sender, MouseEventArgs e)
{
- if (IsEnabled)
+ if (IsEnabled && DotScale != null)
{
DotScale.BeginAnimation(ScaleTransform.ScaleXProperty, FactoryAnimation.CreateIn(1, 1.1, 0.15, useCubicEase: true));
DotScale.BeginAnimation(ScaleTransform.ScaleYProperty, FactoryAnimation.CreateIn(1, 1.1, 0.15, useCubicEase: true));
@@ -227,12 +252,11 @@ namespace GTweak.Assets.UserControls
private void Toggle_MouseLeave(object sender, MouseEventArgs e)
{
- if (IsEnabled)
+ if (IsEnabled && DotScale != null)
{
DotScale.BeginAnimation(ScaleTransform.ScaleXProperty, FactoryAnimation.CreateIn(1.1, 1, 0.15, useCubicEase: true));
DotScale.BeginAnimation(ScaleTransform.ScaleYProperty, FactoryAnimation.CreateIn(1.1, 1, 0.15, useCubicEase: true));
}
}
-
}
-}
+}
\ No newline at end of file
diff --git a/.Source/GTweak/Core/RelayCommand.cs b/.Source/GTweak/Core/RelayCommand.cs
index ea0e892e..527b7586 100644
--- a/.Source/GTweak/Core/RelayCommand.cs
+++ b/.Source/GTweak/Core/RelayCommand.cs
@@ -13,13 +13,16 @@ namespace GTweak.Core
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
- public RelayCommand(Action<object> _execute, Func<object, bool> _canExecute = null)
+
+ public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
- this._execute = _execute;
- this._canExecute = _canExecute;
+ _execute = execute ?? (obj => { });
+ _canExecute = canExecute ?? (obj => true);
}
- public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);
- public void Execute(object parameter) => _execute?.Invoke(parameter);
+
+ public bool CanExecute(object parameter) => _canExecute(parameter);
+
+ public void Execute(object parameter) => _execute(parameter);
}
}