Skip to content

Commit 83dc26e

Browse files
committed
Fix crash on changing app resource before app resource assigned
1 parent d36c6a9 commit 83dc26e

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

CollapseLauncher/Classes/Extension/UIElementExtensions.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -390,13 +390,15 @@ internal static TextBlock AddTextBlockLine(this TextBlock textBlock, string mess
390390
return textBlock;
391391
}
392392

393-
private static ResourceDictionary _currentDictionary;
393+
[field: AllowNull, MaybeNull]
394+
private static ResourceDictionary CurrentDictionary
395+
{
396+
get => field ??= Application.Current.Resources ?? throw new NullReferenceException("Application.Current.Resources is null or not initialized!");
397+
}
394398

395399
internal static TReturnType GetApplicationResource<TReturnType>(string resourceKey)
396400
{
397-
_currentDictionary ??= Application.Current.Resources;
398-
399-
if (!(_currentDictionary?.TryGetValue(resourceKey, out object resourceObj) ?? false))
401+
if (!CurrentDictionary.TryGetValue(resourceKey, out object resourceObj))
400402
throw new KeyNotFoundException($"Application resource with key: {resourceKey} does not exist!");
401403

402404
if (resourceObj is not TReturnType resource)
@@ -408,9 +410,7 @@ internal static TReturnType GetApplicationResource<TReturnType>(string resourceK
408410
internal static ref TReturnType GetApplicationResourceRef<TReturnType>(string resourceKey)
409411
where TReturnType : struct
410412
{
411-
_currentDictionary ??= Application.Current.Resources;
412-
413-
if (!(_currentDictionary?.TryGetValue(resourceKey, out object resourceObj) ?? false))
413+
if (!CurrentDictionary.TryGetValue(resourceKey, out object resourceObj))
414414
{
415415
return ref Unsafe.NullRef<TReturnType>();
416416
}
@@ -420,10 +420,10 @@ internal static ref TReturnType GetApplicationResourceRef<TReturnType>(string re
420420

421421
internal static void SetApplicationResource(string resourceKey, object value)
422422
{
423-
if (!_currentDictionary.ContainsKey(resourceKey))
423+
if (!CurrentDictionary.ContainsKey(resourceKey))
424424
throw new KeyNotFoundException($"Application resource with key: {resourceKey} does not exist!");
425425

426-
_currentDictionary[resourceKey] = value;
426+
CurrentDictionary[resourceKey] = value;
427427
}
428428

429429
internal static CornerRadius GetElementCornerRadius(FrameworkElement element, CornerRadiusKind kind = CornerRadiusKind.Normal)

0 commit comments

Comments
 (0)