diff --git a/Microsoft.Toolkit.Future/Adorners/AdornerLayer.cs b/Microsoft.Toolkit.Future/Adorners/AdornerLayer.cs
index 056c283..1c6bae5 100644
--- a/Microsoft.Toolkit.Future/Adorners/AdornerLayer.cs
+++ b/Microsoft.Toolkit.Future/Adorners/AdornerLayer.cs
@@ -1,4 +1,4 @@
-// Licensed to the .NET Foundation under one or more agreements.
+// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
@@ -16,20 +16,14 @@ namespace CommunityToolkit.WinUI.Controls.Future;
///
public partial class AdornerLayer : Canvas
{
- public static UIElement GetXaml(FrameworkElement obj)
- {
- return (UIElement)obj.GetValue(XamlProperty);
- }
+ public static UIElement GetXaml(FrameworkElement obj) => (UIElement)obj.GetValue(XamlProperty);
///
/// Sets the of a . Use this to attach any as an adorner to another . Requires that an is available in the visual tree above the adorned element.
///
///
///
- public static void SetXaml(FrameworkElement obj, UIElement value)
- {
- obj.SetValue(XamlProperty, value);
- }
+ public static void SetXaml(FrameworkElement obj, UIElement value) => obj.SetValue(XamlProperty, value);
///
/// Identifies the Xaml Attached Property.
diff --git a/Microsoft.Toolkit.Future/Converters/CollectionContainsConverter.cs b/Microsoft.Toolkit.Future/Converters/CollectionContainsConverter.cs
index 49bb1ac..7bdab08 100644
--- a/Microsoft.Toolkit.Future/Converters/CollectionContainsConverter.cs
+++ b/Microsoft.Toolkit.Future/Converters/CollectionContainsConverter.cs
@@ -35,7 +35,5 @@ public object Convert(object value, Type targetType, object parameter, string la
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
- {
- throw new NotImplementedException();
- }
+ => throw new NotImplementedException();
}
diff --git a/Microsoft.Toolkit.Future/Data/Grouping.cs b/Microsoft.Toolkit.Future/Data/Grouping.cs
index 2c432fa..c2cf41c 100644
--- a/Microsoft.Toolkit.Future/Data/Grouping.cs
+++ b/Microsoft.Toolkit.Future/Data/Grouping.cs
@@ -12,42 +12,25 @@
namespace Microsoft.Toolkit.Future.Data;
-public class Grouping : IGrouping, IEnumerable, IEnumerable, ICollectionViewGroup
+public class Grouping(TKey key, IEnumerable items) : IGrouping, IEnumerable, IEnumerable, ICollectionViewGroup
{
public object Group => Key;
public IObservableVector
public class Mouse
{
- private static readonly object _cursorLock = new object();
- private static readonly CoreCursor _defaultCursor = new CoreCursor(CoreCursorType.Arrow, 1);
+ private static readonly object _cursorLock = new();
+ private static readonly CoreCursor _defaultCursor = new(CoreCursorType.Arrow, 1);
private static readonly Dictionary _cursors =
- new Dictionary { { CoreCursorType.Arrow, _defaultCursor } };
+ new() { { CoreCursorType.Arrow, _defaultCursor } };
///
/// Dependency property for specifying the target to be shown
@@ -32,20 +32,14 @@ public class Mouse
///
/// Object where the selector cursor type should be shown.
/// Target cursor type value.
- public static void SetCursor(FrameworkElement element, CoreCursorType value)
- {
- element.SetValue(CursorProperty, value);
- }
+ public static void SetCursor(FrameworkElement element, CoreCursorType value) => element.SetValue(CursorProperty, value);
///
/// Get the current .
///
/// Object where the selector cursor type should be shown.
/// Cursor type set on target element.
- public static CoreCursorType GetCursor(FrameworkElement element)
- {
- return (CoreCursorType)element.GetValue(CursorProperty);
- }
+ public static CoreCursorType GetCursor(FrameworkElement element) => (CoreCursorType)element.GetValue(CursorProperty);
private static void CursorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
@@ -97,10 +91,8 @@ private static void Element_PointerExited(object sender, PointerRoutedEventArgs
Window.Current.CoreWindow.PointerCursor = cursor;
}
- private static void ElementOnUnloaded(object sender, RoutedEventArgs routedEventArgs)
- {
+ private static void ElementOnUnloaded(object sender, RoutedEventArgs routedEventArgs) =>
// when the element is programatically unloaded, reset the cursor back to default
// this is necessary when click triggers immediate change in layout and PointerExited is not called
Window.Current.CoreWindow.PointerCursor = _defaultCursor;
- }
-}
\ No newline at end of file
+}
diff --git a/Microsoft.Toolkit.Future/Extensions/NavigationView/NavigationViewExtensions.cs b/Microsoft.Toolkit.Future/Extensions/NavigationView/NavigationViewExtensions.cs
index 6c6c581..f7b22d0 100644
--- a/Microsoft.Toolkit.Future/Extensions/NavigationView/NavigationViewExtensions.cs
+++ b/Microsoft.Toolkit.Future/Extensions/NavigationView/NavigationViewExtensions.cs
@@ -23,20 +23,14 @@ public class NavigationViewExtensions
///
/// The .
/// The selected index.
- public static int GetSelectedIndex(NavigationView obj)
- {
- return (int)obj.GetValue(SelectedIndexProperty);
- }
+ public static int GetSelectedIndex(NavigationView obj) => (int)obj.GetValue(SelectedIndexProperty);
///
/// Sets the index of the selected .
///
/// The .
/// The index to select.
- public static void SetSelectedIndex(NavigationView obj, int value)
- {
- obj.SetValue(SelectedIndexProperty, value);
- }
+ public static void SetSelectedIndex(NavigationView obj, int value) => obj.SetValue(SelectedIndexProperty, value);
///
/// Attached for binding the selected index of a .
@@ -48,20 +42,14 @@ public static void SetSelectedIndex(NavigationView obj, int value)
///
/// The .
/// True if the settings page is selected.
- public static bool GetIsSettingsSelected(NavigationView obj)
- {
- return (bool)obj.GetValue(IsSettingsSelectedProperty);
- }
+ public static bool GetIsSettingsSelected(NavigationView obj) => (bool)obj.GetValue(IsSettingsSelectedProperty);
///
/// Sets a value representing if the settings page is selected for the .
///
/// The .
/// Set to True to select the settings page.
- public static void SetIsSettingsSelected(NavigationView obj, bool value)
- {
- obj.SetValue(IsSettingsSelectedProperty, value);
- }
+ public static void SetIsSettingsSelected(NavigationView obj, bool value) => obj.SetValue(IsSettingsSelectedProperty, value);
///
/// Attached for selecting the Settings Page of a .
@@ -74,20 +62,14 @@ public static void SetIsSettingsSelected(NavigationView obj, bool value)
///
/// The .
/// True if the feature is on.
- public static bool GetCollapseOnClick(NavigationView obj)
- {
- return (bool)obj.GetValue(CollapseOnClickProperty);
- }
+ public static bool GetCollapseOnClick(NavigationView obj) => (bool)obj.GetValue(CollapseOnClickProperty);
///
/// Sets the behavior to collapse the content when clicking the already selected .
///
/// The .
/// True to turn on this feature.
- public static void SetCollapseOnClick(NavigationView obj, bool value)
- {
- obj.SetValue(CollapseOnClickProperty, value);
- }
+ public static void SetCollapseOnClick(NavigationView obj, bool value) => obj.SetValue(CollapseOnClickProperty, value);
///
/// Attached for enabling the behavior to collapse the content when the same selected item is invoked again (click or tap).
diff --git a/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotCloseButtonCommandConverter.cs b/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotCloseButtonCommandConverter.cs
index cd7b134..0e0ee16 100644
--- a/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotCloseButtonCommandConverter.cs
+++ b/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotCloseButtonCommandConverter.cs
@@ -28,7 +28,5 @@ public object Convert(object value, Type targetType, object parameter, string la
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
- {
- throw new NotImplementedException();
- }
+ => throw new NotImplementedException();
}
diff --git a/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotGlyphConverter.cs b/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotGlyphConverter.cs
index 7441573..5804d0c 100644
--- a/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotGlyphConverter.cs
+++ b/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotGlyphConverter.cs
@@ -29,7 +29,5 @@ public override object Convert(object value, Type targetType, object parameter,
}
public override object ConvertBack(object value, Type targetType, object parameter, string language)
- {
- throw new NotImplementedException();
- }
+ => throw new NotImplementedException();
}
diff --git a/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotImageConverter.cs b/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotImageConverter.cs
index 15b9664..40d378d 100644
--- a/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotImageConverter.cs
+++ b/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotImageConverter.cs
@@ -28,7 +28,5 @@ public override object Convert(object value, Type targetType, object parameter,
}
public override object ConvertBack(object value, Type targetType, object parameter, string language)
- {
- throw new NotImplementedException();
- }
+ => throw new NotImplementedException();
}
diff --git a/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotItemConverter.cs b/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotItemConverter.cs
index 5873c41..eb38850 100644
--- a/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotItemConverter.cs
+++ b/Microsoft.Toolkit.Future/Extensions/Pivot/GetPivotItemConverter.cs
@@ -34,7 +34,5 @@ public virtual object Convert(object value, Type targetType, object parameter, s
}
public virtual object ConvertBack(object value, Type targetType, object parameter, string language)
- {
- throw new NotImplementedException();
- }
+ => throw new NotImplementedException();
}
diff --git a/Microsoft.Toolkit.Future/Extensions/Pivot/PivotExtensions.Properties.cs b/Microsoft.Toolkit.Future/Extensions/Pivot/PivotExtensions.Properties.cs
index 0dfadb8..002d6e7 100644
--- a/Microsoft.Toolkit.Future/Extensions/Pivot/PivotExtensions.Properties.cs
+++ b/Microsoft.Toolkit.Future/Extensions/Pivot/PivotExtensions.Properties.cs
@@ -21,9 +21,7 @@ public partial class PivotExtensions
/// The from which to get the associated instance
/// The instance associated with the the or null
public static Style GetPivotHeaderItemStyle(Windows.UI.Xaml.Controls.Pivot obj)
- {
- return (Style)obj.GetValue(PivotHeaderItemStyleProperty);
- }
+ => (Style)obj.GetValue(PivotHeaderItemStyleProperty);
///
/// Sets the instance assocaited with the specified
@@ -31,9 +29,7 @@ public static Style GetPivotHeaderItemStyle(Windows.UI.Xaml.Controls.Pivot obj)
/// The to associated the instance to
/// The instance to bind to the
public static void SetPivotHeaderItemStyle(Windows.UI.Xaml.Controls.Pivot obj, Style value)
- {
- obj.SetValue(PivotHeaderItemStyleProperty, value);
- }
+ => obj.SetValue(PivotHeaderItemStyleProperty, value);
///
/// Attached for binding a as an alternate template to a
@@ -46,20 +42,14 @@ public static void SetPivotHeaderItemStyle(Windows.UI.Xaml.Controls.Pivot obj, S
///
/// PivotItem to get value from.
/// String value for FontIcon.
- public static string GetGlyph(PivotItem obj)
- {
- return (string)obj.GetValue(GlyphProperty);
- }
+ public static string GetGlyph(PivotItem obj) => (string)obj.GetValue(GlyphProperty);
///
/// Sets the attached property value for Glyph.
///
/// PivotItem to set value for.
/// String value for FontIcon.
- public static void SetGlyph(PivotItem obj, string value)
- {
- obj.SetValue(GlyphProperty, value);
- }
+ public static void SetGlyph(PivotItem obj, string value) => obj.SetValue(GlyphProperty, value);
///
/// Used with the Pivot Styles to specify a FontIcon Glyph using the Segoe MDL2 Assets font.
@@ -72,20 +62,14 @@ public static void SetGlyph(PivotItem obj, string value)
///
/// PivotItem to get value from.
/// Resource to use for an Image in the MSEdgeTabStyle.
- public static ImageSource GetImageSource(PivotItem obj)
- {
- return (ImageSource)obj.GetValue(ImageSourceProperty);
- }
+ public static ImageSource GetImageSource(PivotItem obj) => (ImageSource)obj.GetValue(ImageSourceProperty);
///
/// Sets the attached property value for ImageSource.
///
/// PivotItem to set value for.
/// Resource to use for an Image in the MSEdgeTabStyle.
- public static void SetImageSource(PivotItem obj, ImageSource value)
- {
- obj.SetValue(ImageSourceProperty, value);
- }
+ public static void SetImageSource(PivotItem obj, ImageSource value) => obj.SetValue(ImageSourceProperty, value);
///
/// Used with the Pivot Styles to specify an ImageSource for the MSEdgeTabStyle.
@@ -98,10 +82,8 @@ public static void SetImageSource(PivotItem obj, ImageSource value)
///
/// Pivot to get value from.
/// Command value for the MSEdgeTabStyle Close Button.
- public static ICommand GetCloseButtonCommand(Windows.UI.Xaml.Controls.Pivot obj) // TODO: Should this be per PivotHeaderItem? Thinking no?
- {
- return (ICommand)obj.GetValue(CloseButtonCommandProperty);
- }
+ public static ICommand GetCloseButtonCommand(Windows.UI.Xaml.Controls.Pivot obj)
+ => (ICommand)obj.GetValue(CloseButtonCommandProperty); // TODO: Should this be per PivotHeaderItem? Thinking no?
///
/// Sets the attached property value for CloseButtonCommand.
@@ -109,9 +91,7 @@ public static ICommand GetCloseButtonCommand(Windows.UI.Xaml.Controls.Pivot obj)
/// Pivot to set value for.
/// Command value for the MSEdgeTabStyle Close Button.
public static void SetCloseButtonCommand(Windows.UI.Xaml.Controls.Pivot obj, ICommand value)
- {
- obj.SetValue(CloseButtonCommandProperty, value);
- }
+ => obj.SetValue(CloseButtonCommandProperty, value);
///
/// Used with the MSEdgeTab Pivot Styles to specify a Close Command for the Tab's Close Button.
@@ -124,20 +104,14 @@ public static void SetCloseButtonCommand(Windows.UI.Xaml.Controls.Pivot obj, ICo
///
/// Pivot to get value from.
/// False is content will be hidden.
- public static bool GetIsContentVisible(Windows.UI.Xaml.Controls.Pivot obj)
- {
- return (bool)obj.GetValue(IsContentVisibleProperty);
- }
+ public static bool GetIsContentVisible(Windows.UI.Xaml.Controls.Pivot obj) => (bool)obj.GetValue(IsContentVisibleProperty);
///
/// Sets the attached property value for IsContentVisible.
///
/// Pivot to set value for.
/// Set to false to hide the PivotItemsPresenter.
- public static void SetIsContentVisible(Windows.UI.Xaml.Controls.Pivot obj, bool value)
- {
- obj.SetValue(IsContentVisibleProperty, value);
- }
+ public static void SetIsContentVisible(Windows.UI.Xaml.Controls.Pivot obj, bool value) => obj.SetValue(IsContentVisibleProperty, value);
///
/// Used to hide the content of a Pivot to just use the Pivot Header Items.
diff --git a/Microsoft.Toolkit.Future/Extensions/SymbolIcon/SymbolIconExtensions.cs b/Microsoft.Toolkit.Future/Extensions/SymbolIcon/SymbolIconExtensions.cs
index bbf0fda..9c8ea02 100644
--- a/Microsoft.Toolkit.Future/Extensions/SymbolIcon/SymbolIconExtensions.cs
+++ b/Microsoft.Toolkit.Future/Extensions/SymbolIcon/SymbolIconExtensions.cs
@@ -14,15 +14,9 @@ namespace CommunityToolkit.WinUI.Extensions.Future;
[Bindable]
public class SymbolIconExtensions
{
- public static double GetFontSize(SymbolIcon obj)
- {
- return (double)obj.GetValue(FontSizeProperty);
- }
+ public static double GetFontSize(SymbolIcon obj) => (double)obj.GetValue(FontSizeProperty);
- public static void SetFontSize(SymbolIcon obj, double value)
- {
- obj.SetValue(FontSizeProperty, value);
- }
+ public static void SetFontSize(SymbolIcon obj, double value) => obj.SetValue(FontSizeProperty, value);
// Using a DependencyProperty as the backing store for FontSize. This enables animation, styling, binding, etc...
public static readonly DependencyProperty FontSizeProperty =
diff --git a/XamlStudio.Toolkit.UnitTests/UnitTestApp.xaml.cs b/XamlStudio.Toolkit.UnitTests/UnitTestApp.xaml.cs
index cf0c71f..7136d0a 100644
--- a/XamlStudio.Toolkit.UnitTests/UnitTestApp.xaml.cs
+++ b/XamlStudio.Toolkit.UnitTests/UnitTestApp.xaml.cs
@@ -34,17 +34,13 @@ public static FrameworkElement? ContentRoot
}
// Abstract CoreApplication.MainView.DispatcherQueue
- public static DispatcherQueue DispatcherQueue
- {
- get
- {
+ public static DispatcherQueue DispatcherQueue =>
#if !WINAPPSDK
- return CoreApplication.MainView.DispatcherQueue;
+ CoreApplication.MainView.DispatcherQueue;
#else
- return currentWindow.DispatcherQueue;
+ currentWindow.DispatcherQueue;
#endif
- }
- }
+
///
/// Initializes the singleton application object. This is the first line of authored code
@@ -101,10 +97,7 @@ protected override void OnLaunched(LaunchActivatedEventArgs e)
///
/// The Frame which failed navigation
/// Details about the navigation failure
- void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
- {
- throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
- }
+ void OnNavigationFailed(object sender, NavigationFailedEventArgs e) => throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
///
/// Invoked when application execution is being suspended. Application state is saved
diff --git a/XamlStudio.Toolkit.UnitTests/XmlToXamlTreeTests.cs b/XamlStudio.Toolkit.UnitTests/XmlToXamlTreeTests.cs
index f3d2031..4dc73fd 100644
--- a/XamlStudio.Toolkit.UnitTests/XmlToXamlTreeTests.cs
+++ b/XamlStudio.Toolkit.UnitTests/XmlToXamlTreeTests.cs
@@ -23,465 +23,451 @@ public class XmlToXamlTreeTests : VisualUITestBase
{
[TestMethod]
public async Task Basic_XmlToXamlTest()
- {
- await EnqueueAsync(async () =>
- {
- var xaml =
- """
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- """;
-
- var fwe = XamlReader.Load(xaml) as FrameworkElement;
- var xml = Parser.ParseText(xaml);
-
- await LoadTestContentAsync(fwe);
-
- XamlXmlTreeCoordinator coordinator = new();
- coordinator.Initialize(xml, fwe);
-
- var grid = fwe.FindChild("RootGrid");
- Assert.IsTrue(coordinator.TryGetXmlElement(grid, out var gridNode));
- if (gridNode is IXmlElementSyntax gridElement)
+ => await EnqueueAsync(async () =>
{
- Assert.AreEqual("RootGrid", gridElement.GetAttributeValue("Name", "x"));
- }
- else
- {
- Assert.Fail("Xml Node not an Element for Grid");
- }
+ var xaml =
+ """
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ """;
+
+ var fwe = XamlReader.Load(xaml) as FrameworkElement;
+ var xml = Parser.ParseText(xaml);
+
+ await LoadTestContentAsync(fwe);
+
+ XamlXmlTreeCoordinator coordinator = new();
+ coordinator.Initialize(xml, fwe);
+
+ var grid = fwe.FindChild("RootGrid");
+ Assert.IsTrue(coordinator.TryGetXmlElement(grid, out var gridNode));
+ if (gridNode is IXmlElementSyntax gridElement)
+ {
+ Assert.AreEqual("RootGrid", gridElement.GetAttributeValue("Name", "x"));
+ }
+ else
+ {
+ Assert.Fail("Xml Node not an Element for Grid");
+ }
- var textblockNode = xml.FindNode(xaml.IndexOf("
- {
- var xaml =
- """
-
-
-
-
- #XAMLing
- /ˈzæməlɪŋ/
- verb [With XAML Studio]
-
-
-
-
-
- .
-
-
-
-
+ => await EnqueueAsync(async () =>
+ {
+ var xaml =
+ """
+
+
-
-
+
+ #XAMLing
+ /ˈzæməlɪŋ/
+ verb [With XAML Studio]
+
+
+
+
+
+ .
+
+
+
+
+
+
+
+
-
-
- """;
+
+ """;
- var fwe = XamlReader.Load(xaml) as FrameworkElement;
- var xml = Parser.ParseText(xaml);
+ var fwe = XamlReader.Load(xaml) as FrameworkElement;
+ var xml = Parser.ParseText(xaml);
- await LoadTestContentAsync(fwe);
+ await LoadTestContentAsync(fwe);
- XamlXmlTreeCoordinator coordinator = new();
- coordinator.Initialize(xml, fwe);
+ XamlXmlTreeCoordinator coordinator = new();
+ coordinator.Initialize(xml, fwe);
- var sp1Index = xaml.IndexOf("");
- var sp1Node = xml.FindNode(sp1Index + 1).ParentElement;
- var sp2Node = xml.FindNode(xaml.IndexOf("", sp1Index + 1) + 1).ParentElement;
+ var sp1Index = xaml.IndexOf("");
+ var sp1Node = xml.FindNode(sp1Index + 1).ParentElement;
+ var sp2Node = xml.FindNode(xaml.IndexOf("", sp1Index + 1) + 1).ParentElement;
- var sp1 = fwe.FindChild();
- Assert.IsTrue(coordinator.TryGetXmlElement(sp1, out var sp1NodeRetrieved), "First StackPanel Xml node wasn't Element");
- Assert.AreEqual(sp1Node, sp1NodeRetrieved, "First StackPanel XML Element didn't match.");
+ var sp1 = fwe.FindChild();
+ Assert.IsTrue(coordinator.TryGetXmlElement(sp1, out var sp1NodeRetrieved), "First StackPanel Xml node wasn't Element");
+ Assert.AreEqual(sp1Node, sp1NodeRetrieved, "First StackPanel XML Element didn't match.");
- var sp2 = sp1.FindChild();
- Assert.IsTrue(coordinator.TryGetXmlElement(sp2, out var sp2NodeRetrieved), "Second StackPanel Xml node wasn't Element");
- Assert.AreEqual(sp2Node, sp2NodeRetrieved, "Second StackPanel XML Element didn't match.");
+ var sp2 = sp1.FindChild();
+ Assert.IsTrue(coordinator.TryGetXmlElement(sp2, out var sp2NodeRetrieved), "Second StackPanel Xml node wasn't Element");
+ Assert.AreEqual(sp2Node, sp2NodeRetrieved, "Second StackPanel XML Element didn't match.");
- Assert.AreEqual(7, coordinator.Count, "Expected 7 elements to be mapped.");
+ Assert.AreEqual(7, coordinator.Count, "Expected 7 elements to be mapped.");
- await UnloadTestContentAsync(fwe);
- });
- }
+ await UnloadTestContentAsync(fwe);
+ });
[TestMethod]
public async Task ColorConversion_XmlToXamlTest()
- {
- await EnqueueAsync(async () =>
- {
- var xaml =
- """
-
-
-
-
-
-
-
-
- """;
-
- var fwe = XamlReader.Load(xaml) as FrameworkElement;
- var xml = Parser.ParseText(xaml);
-
- await LoadTestContentAsync(fwe);
-
- XamlXmlTreeCoordinator coordinator = new();
- coordinator.Initialize(xml, fwe);
-
- var sp = fwe.FindChild();
- Assert.IsTrue(coordinator.TryGetXmlElement(sp, out var spNode));
- if (spNode is not IXmlElementSyntax)
+ => await EnqueueAsync(async () =>
{
- Assert.Fail("Xml Node not an Element for StackPanel");
- }
+ var xaml =
+ """
+
- var colorMatches = new[]
- {
- Colors.Blue,
- Color.FromArgb(255, 255, 0, 0),
- Color.FromArgb(255, 0, 0, 255),
- };
- var i = 0;
- var j = 0;
-
- Assert.AreEqual(3, sp.Children.Count, "Expected StackPanel to have 3 children");
- foreach (var child in sp.Children)
- {
- i = xaml.IndexOf("
+
+
+
+
+
+ """;
+
+ var fwe = XamlReader.Load(xaml) as FrameworkElement;
+ var xml = Parser.ParseText(xaml);
+
+ await LoadTestContentAsync(fwe);
+
+ XamlXmlTreeCoordinator coordinator = new();
+ coordinator.Initialize(xml, fwe);
+
+ var sp = fwe.FindChild();
+ Assert.IsTrue(coordinator.TryGetXmlElement(sp, out var spNode));
+ if (spNode is not IXmlElementSyntax)
{
- Assert.IsTrue(coordinator.TryGetVisualElement(nodeElement, out var element));
- if (element is Border border
- && element == child)
- {
- Assert.AreEqual(colorMatches[j++], (border.Background as SolidColorBrush).Color, $"Unexpected color for Border[{j - 1}]");
- }
- else
+ Assert.Fail("Xml Node not an Element for StackPanel");
+ }
+
+ var colorMatches = new[]
+ {
+ Colors.Blue,
+ Color.FromArgb(255, 255, 0, 0),
+ Color.FromArgb(255, 0, 0, 255),
+ };
+ var i = 0;
+ var j = 0;
+
+ Assert.AreEqual(3, sp.Children.Count, "Expected StackPanel to have 3 children");
+ foreach (var child in sp.Children)
+ {
+ i = xaml.IndexOf("
- {
- var xaml =
- """
-
-
-
-
-
-
-
-
-
- """;
-
- var fwe = XamlReader.Load(xaml) as FrameworkElement;
- var xml = Parser.ParseText(xaml);
-
- await LoadTestContentAsync(fwe);
-
- XamlXmlTreeCoordinator coordinator = new();
- coordinator.Initialize(xml, fwe);
-
- var sp = fwe.FindChild();
- Assert.IsTrue(coordinator.TryGetXmlElement(sp, out var spNode));
- if (spNode is not IXmlElementSyntax)
+ => await EnqueueAsync(async () =>
{
- Assert.Fail("Xml Node not an Element for StackPanel");
- }
+ var xaml =
+ """
+
+
+
+
+
+
+
+
+
+ """;
- var uriMatches = new[]
- {
- "ms-appx:///Assets/StoreLogo.png",
- "ms-appx:///Assets/SplashScreen.png",
- "ms-resource:///Files/Assets/StoreLogo.png", // Gets converted to ms-resource:// path prepended with /Files by System
- "https://picsum.photos/200/200",
- };
- var i = 0;
- var j = 0;
-
- Assert.AreEqual(4, sp.Children.Count, "Expected StackPanel to have 3 children");
- foreach (var child in sp.Children)
- {
- i = xaml.IndexOf("();
+ Assert.IsTrue(coordinator.TryGetXmlElement(sp, out var spNode));
+ if (spNode is not IXmlElementSyntax)
{
- Assert.IsTrue(coordinator.TryGetVisualElement(nodeElement, out var element));
- if (element is Image image
- && element == child)
- {
- Assert.AreEqual(uriMatches[j++], (image.Source as BitmapImage).UriSource.AbsoluteUri, $"Unexpected uri for Image[{j - 1}]");
- }
- else
+ Assert.Fail("Xml Node not an Element for StackPanel");
+ }
+
+ var uriMatches = new[]
+ {
+ "ms-appx:///Assets/StoreLogo.png",
+ "ms-appx:///Assets/SplashScreen.png",
+ "ms-resource:///Files/Assets/StoreLogo.png", // Gets converted to ms-resource:// path prepended with /Files by System
+ "https://picsum.photos/200/200",
+ };
+ var i = 0;
+ var j = 0;
+
+ Assert.AreEqual(4, sp.Children.Count, "Expected StackPanel to have 3 children");
+ foreach (var child in sp.Children)
+ {
+ i = xaml.IndexOf("
- {
- var xaml =
- """
-
-
-
-
-
-
-
-
-
-
-
- """;
-
- var fwe = XamlReader.Load(xaml) as FrameworkElement;
- var xml = Parser.ParseText(xaml);
-
- await LoadTestContentAsync(fwe);
-
- XamlXmlTreeCoordinator coordinator = new();
- coordinator.Initialize(xml, fwe);
-
- var tabview = fwe.FindChild("MyTabView");
- Assert.IsTrue(coordinator.TryGetXmlElement(tabview, out var tabviewNode));
- if (tabviewNode is IXmlElementSyntax tabviewElement)
- {
- Assert.AreEqual("MyTabView", tabviewElement.GetAttributeValue("Name", "x"));
- }
- else
+ => await EnqueueAsync(async () =>
{
- Assert.Fail("Xml Node not an Element for TabView");
- }
+ var xaml =
+ """
+
+
+
+
+
+
+
+
+
+
+
+ """;
+
+ var fwe = XamlReader.Load(xaml) as FrameworkElement;
+ var xml = Parser.ParseText(xaml);
+
+ await LoadTestContentAsync(fwe);
+
+ XamlXmlTreeCoordinator coordinator = new();
+ coordinator.Initialize(xml, fwe);
+
+ var tabview = fwe.FindChild("MyTabView");
+ Assert.IsTrue(coordinator.TryGetXmlElement(tabview, out var tabviewNode));
+ if (tabviewNode is IXmlElementSyntax tabviewElement)
+ {
+ Assert.AreEqual("MyTabView", tabviewElement.GetAttributeValue("Name", "x"));
+ }
+ else
+ {
+ Assert.Fail("Xml Node not an Element for TabView");
+ }
- var tabviewitemNode = xml.FindNode(xaml.IndexOf("
- {
- var xaml =
- """
-
-
-
-
-
-
-
-
- """;
-
- var fwe = XamlReader.Load(xaml) as FrameworkElement;
- var xml = Parser.ParseText(xaml);
-
- await LoadTestContentAsync(fwe);
-
- XamlXmlTreeCoordinator coordinator = new();
- coordinator.Initialize(xml, fwe);
-
- var listview = fwe.FindChild("MyListView");
- Assert.IsTrue(coordinator.TryGetXmlElement(listview, out var listviewNode));
- if (listviewNode is IXmlElementSyntax listviewElement)
+ => await EnqueueAsync(async () =>
{
- Assert.AreEqual("MyListView", listviewElement.GetAttributeValue("Name", "x"));
- }
- else
- {
- Assert.Fail("Xml Node not an Element for ListView");
- }
+ var xaml =
+ """
+
+
+
+
+
+
+
+
+ """;
+
+ var fwe = XamlReader.Load(xaml) as FrameworkElement;
+ var xml = Parser.ParseText(xaml);
+
+ await LoadTestContentAsync(fwe);
+
+ XamlXmlTreeCoordinator coordinator = new();
+ coordinator.Initialize(xml, fwe);
+
+ var listview = fwe.FindChild("MyListView");
+ Assert.IsTrue(coordinator.TryGetXmlElement(listview, out var listviewNode));
+ if (listviewNode is IXmlElementSyntax listviewElement)
+ {
+ Assert.AreEqual("MyListView", listviewElement.GetAttributeValue("Name", "x"));
+ }
+ else
+ {
+ Assert.Fail("Xml Node not an Element for ListView");
+ }
- Assert.AreEqual(4, coordinator.Count, "Expected 4 elements to be mapped.");
+ Assert.AreEqual(4, coordinator.Count, "Expected 4 elements to be mapped.");
- await UnloadTestContentAsync(fwe);
- });
- }
+ await UnloadTestContentAsync(fwe);
+ });
[TestMethod]
public async Task ListViewComplex_XmlToXamlTest()
- {
- await EnqueueAsync(async () =>
- {
- var xaml =
- """
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- """;
-
- var fwe = XamlReader.Load(xaml) as FrameworkElement;
- var xml = Parser.ParseText(xaml);
-
- await LoadTestContentAsync(fwe);
-
- XamlXmlTreeCoordinator coordinator = new();
- coordinator.Initialize(xml, fwe);
-
- var listview = fwe.FindChild("MyListView");
- Assert.IsTrue(coordinator.TryGetXmlElement(listview, out var listviewNode));
- if (listviewNode is IXmlElementSyntax listviewElement)
+ => await EnqueueAsync(async () =>
{
- Assert.AreEqual("MyListView", listviewElement.GetAttributeValue("Name", "x"));
- }
- else
- {
- Assert.Fail("Xml Node not an Element for ListView");
- }
+ var xaml =
+ """
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ """;
+
+ var fwe = XamlReader.Load(xaml) as FrameworkElement;
+ var xml = Parser.ParseText(xaml);
+
+ await LoadTestContentAsync(fwe);
+
+ XamlXmlTreeCoordinator coordinator = new();
+ coordinator.Initialize(xml, fwe);
+
+ var listview = fwe.FindChild("MyListView");
+ Assert.IsTrue(coordinator.TryGetXmlElement(listview, out var listviewNode));
+ if (listviewNode is IXmlElementSyntax listviewElement)
+ {
+ Assert.AreEqual("MyListView", listviewElement.GetAttributeValue("Name", "x"));
+ }
+ else
+ {
+ Assert.Fail("Xml Node not an Element for ListView");
+ }
- Assert.AreEqual(2, coordinator.Count, "Expected 2 elements to be mapped.");
+ Assert.AreEqual(2, coordinator.Count, "Expected 2 elements to be mapped.");
- await UnloadTestContentAsync(fwe);
- });
- }
-}
\ No newline at end of file
+ await UnloadTestContentAsync(fwe);
+ });
+}
diff --git a/XamlStudio.Toolkit/Controls/ResourceViewer/Helpers/ColorToHexConverter.cs b/XamlStudio.Toolkit/Controls/ResourceViewer/Helpers/ColorToHexConverter.cs
index 7583d78..2fcffe1 100644
--- a/XamlStudio.Toolkit/Controls/ResourceViewer/Helpers/ColorToHexConverter.cs
+++ b/XamlStudio.Toolkit/Controls/ResourceViewer/Helpers/ColorToHexConverter.cs
@@ -22,8 +22,5 @@ public object Convert(object value, Type targetType, object parameter, string la
return value;
}
- public object ConvertBack(object value, Type targetType, object parameter, string language)
- {
- throw new NotImplementedException();
- }
+ public object ConvertBack(object value, Type targetType, object parameter, string language) => throw new NotImplementedException();
}
diff --git a/XamlStudio.Toolkit/Controls/ResourceViewer/TemplateSelector.cs b/XamlStudio.Toolkit/Controls/ResourceViewer/TemplateSelector.cs
index c590374..c38e84e 100644
--- a/XamlStudio.Toolkit/Controls/ResourceViewer/TemplateSelector.cs
+++ b/XamlStudio.Toolkit/Controls/ResourceViewer/TemplateSelector.cs
@@ -21,15 +21,9 @@ public TemplateSelector()
{
}
- protected override DataTemplate SelectTemplateCore(object item)
- {
- return LookupDataTemplate(item);
- }
+ protected override DataTemplate SelectTemplateCore(object item) => LookupDataTemplate(item);
- protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
- {
- return LookupDataTemplate(item);
- }
+ protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) => LookupDataTemplate(item);
private DataTemplate LookupDataTemplate(object item)
{
diff --git a/XamlStudio.Toolkit/Converters/ColorToNameConverter.cs b/XamlStudio.Toolkit/Converters/ColorToNameConverter.cs
index 0f0590d..4ee50ff 100644
--- a/XamlStudio.Toolkit/Converters/ColorToNameConverter.cs
+++ b/XamlStudio.Toolkit/Converters/ColorToNameConverter.cs
@@ -40,8 +40,5 @@ public object Convert(object value, Type targetType, object parameter, string la
return null;
}
- public object ConvertBack(object value, Type targetType, object parameter, string language)
- {
- throw new NotImplementedException();
- }
+ public object ConvertBack(object value, Type targetType, object parameter, string language) => throw new NotImplementedException();
}
diff --git a/XamlStudio.Toolkit/Converters/HexToColorConverter.cs b/XamlStudio.Toolkit/Converters/HexToColorConverter.cs
index ba4839b..7e79d83 100644
--- a/XamlStudio.Toolkit/Converters/HexToColorConverter.cs
+++ b/XamlStudio.Toolkit/Converters/HexToColorConverter.cs
@@ -55,8 +55,5 @@ public object Convert(object value, Type targetType, object parameter, string la
return null;
}
- public object ConvertBack(object value, Type targetType, object parameter, string language)
- {
- return Convert(value, targetType, parameter, language);
- }
+ public object ConvertBack(object value, Type targetType, object parameter, string language) => Convert(value, targetType, parameter, language);
}
diff --git a/XamlStudio.Toolkit/Converters/StringToUriConverter.cs b/XamlStudio.Toolkit/Converters/StringToUriConverter.cs
index c940a26..bf45b4d 100644
--- a/XamlStudio.Toolkit/Converters/StringToUriConverter.cs
+++ b/XamlStudio.Toolkit/Converters/StringToUriConverter.cs
@@ -14,9 +14,8 @@ public object Convert(object value, Type targetType, object parameter, string la
{
if (value is string)
{
- Uri result;
- if (Uri.TryCreate(value as string, UriKind.RelativeOrAbsolute, out result))
+ if (Uri.TryCreate(value as string, UriKind.RelativeOrAbsolute, out var result))
{
return result;
}
@@ -25,8 +24,5 @@ public object Convert(object value, Type targetType, object parameter, string la
return null;
}
- public object ConvertBack(object value, Type targetType, object parameter, string language)
- {
- throw new NotImplementedException();
- }
+ public object ConvertBack(object value, Type targetType, object parameter, string language) => throw new NotImplementedException();
}
diff --git a/XamlStudio.Toolkit/Extensions/XmlExtensions.cs b/XamlStudio.Toolkit/Extensions/XmlExtensions.cs
index 810f075..0124212 100644
--- a/XamlStudio.Toolkit/Extensions/XmlExtensions.cs
+++ b/XamlStudio.Toolkit/Extensions/XmlExtensions.cs
@@ -11,10 +11,7 @@ namespace XamlStudio.Toolkit.Extensions;
public static class XmlExtensions
{
- public static XAttribute GetNamedItem(this IEnumerable list, string name)
- {
- return list.Where(item => item.Name == name).FirstOrDefault();
- }
+ public static XAttribute GetNamedItem(this IEnumerable list, string name) => list.Where(item => item.Name == name).FirstOrDefault();
public static IEnumerable GetTypedEnumerator(this XmlNodeList list)
{
diff --git a/XamlStudio.Toolkit/Helpers/Singleton.cs b/XamlStudio.Toolkit/Helpers/Singleton.cs
index d5cccb0..5151540 100644
--- a/XamlStudio.Toolkit/Helpers/Singleton.cs
+++ b/XamlStudio.Toolkit/Helpers/Singleton.cs
@@ -14,13 +14,7 @@ namespace XamlStudio.Toolkit.Helpers;
public static class Singleton
where T : new()
{
- private static ConcurrentDictionary _instances = new ConcurrentDictionary();
+ private static ConcurrentDictionary _instances = new();
- public static T Instance
- {
- get
- {
- return _instances.GetOrAdd(typeof(T), (t) => new T());
- }
- }
+ public static T Instance => _instances.GetOrAdd(typeof(T), (t) => new T());
}
diff --git a/XamlStudio.Toolkit/Helpers/VisualStateWatcher.cs b/XamlStudio.Toolkit/Helpers/VisualStateWatcher.cs
index d10f6b5..3847ef0 100644
--- a/XamlStudio.Toolkit/Helpers/VisualStateWatcher.cs
+++ b/XamlStudio.Toolkit/Helpers/VisualStateWatcher.cs
@@ -16,7 +16,7 @@ public class VisualStateWatcher
public VisualStateWatcher(FrameworkElement element)
{
- Dictionary visualStateGroups = new();
+ Dictionary visualStateGroups = [];
// Get child of the control in visual tree as that'll contain the VSM
// and will be more expected when manipulating a control itself (as that's the element we manipulate).
@@ -33,7 +33,7 @@ public VisualStateWatcher(FrameworkElement element)
gname = $"- Unnamed {gindex++} -";
}
- List visualStates = new();
+ List visualStates = [];
foreach (var state in group.States)
{
visualStates.Add(new VisualStateInfo(state.Name, gname, state == group.CurrentState));
diff --git a/XamlStudio.Toolkit/Models/ConversionRecord.cs b/XamlStudio.Toolkit/Models/ConversionRecord.cs
index bfa692d..f382102 100644
--- a/XamlStudio.Toolkit/Models/ConversionRecord.cs
+++ b/XamlStudio.Toolkit/Models/ConversionRecord.cs
@@ -17,7 +17,7 @@ public class ConversionRecord
public object Result { get; private set; }
- public object ResultOrValue { get { return Result ?? Value; } }
+ public object ResultOrValue => Result ?? Value;
public bool HasResult { get; private set; }
diff --git a/XamlStudio.Toolkit/Models/XamlBindingInfo.cs b/XamlStudio.Toolkit/Models/XamlBindingInfo.cs
index f6ce855..6b9e943 100644
--- a/XamlStudio.Toolkit/Models/XamlBindingInfo.cs
+++ b/XamlStudio.Toolkit/Models/XamlBindingInfo.cs
@@ -38,7 +38,7 @@ public enum XamlBindingState
public uint Line { get; private set; }
public uint Column { get; private set; }
- public int Length { get { return this.OriginalBindingString.Length; } }
+ public int Length => this.OriginalBindingString.Length;
public XAttribute PropertyAttribute { get; set; }
public string PropertyName { get; set; }
@@ -46,7 +46,7 @@ public enum XamlBindingState
public string ElementName { get; set; }
// TODO: Create a Binding Log window in Xaml Studio which shows all binding events and lets you group/sort/search by time, value, status (etc...)
- public ObservableCollection BindingHistory { get; set; } = new ObservableCollection();
+ public ObservableCollection BindingHistory { get; set; } = [];
// TODO: Make Observable?
@@ -55,17 +55,17 @@ public enum XamlBindingState
public XamlRenderService Service { get; internal set; }
- public DateTime FirstSetTime { get { return BindingHistory.Count == 0 ? DateTime.MinValue : BindingHistory.First().TimeStamp; } }
+ public DateTime FirstSetTime => BindingHistory.Count == 0 ? DateTime.MinValue : BindingHistory.First().TimeStamp;
- public DateTime LastConvertedTime { get { return BindingHistory.Count == 0 ? DateTime.MinValue : BindingHistory.Last().TimeStamp; } }
+ public DateTime LastConvertedTime => BindingHistory.Count == 0 ? DateTime.MinValue : BindingHistory.Last().TimeStamp;
- public bool HasBinded { get { return BindingHistory.Count > 0; } }
+ public bool HasBinded => BindingHistory.Count > 0;
- public bool HasConverter { get { return Converter != null; } }
+ public bool HasConverter => Converter != null;
- public object LastConvertedValue { get { return BindingHistory.LastOrDefault()?.Value; } }
+ public object LastConvertedValue => BindingHistory.LastOrDefault()?.Value;
- public object LastConvertedResult { get { return BindingHistory.LastOrDefault()?.Result; } }
+ public object LastConvertedResult => BindingHistory.LastOrDefault()?.Result;
public object LastConvertedResultOrValue
{
@@ -82,12 +82,9 @@ public object LastConvertedResultOrValue
}
}
- public string LastConvertedResultOrValueString
- {
- get { return LastConvertedResultOrValue?.ToString() ?? string.Empty; }
- }
+ public string LastConvertedResultOrValueString => LastConvertedResultOrValue?.ToString() ?? string.Empty;
- public string LastExceptionMessage { get { return BindingHistory.LastOrDefault()?.ExceptionObject.Message; } }
+ public string LastExceptionMessage => BindingHistory.LastOrDefault()?.ExceptionObject.Message;
public XamlBindingState LastKnownBindingState
{
@@ -106,7 +103,7 @@ public XamlBindingState LastKnownBindingState
}
}
- public long BindingCount { get { return BindingHistory.Count; } }
+ public long BindingCount => BindingHistory.Count;
#endregion
public XamlBindingInfo(uint line, uint column, string binding)
diff --git a/XamlStudio.Toolkit/Models/XamlRenderResultContext.cs b/XamlStudio.Toolkit/Models/XamlRenderResultContext.cs
index 392a1d5..74d954f 100644
--- a/XamlStudio.Toolkit/Models/XamlRenderResultContext.cs
+++ b/XamlStudio.Toolkit/Models/XamlRenderResultContext.cs
@@ -10,13 +10,16 @@
namespace XamlStudio.Toolkit.Models;
-public class XamlRenderResultContext
+///
+/// Create a new XamlRenderResultContext for the given initial content.
+///
+/// Initial string passed to render.
+public class XamlRenderResultContext(string initialContent)
{
- private readonly string _content;
///
/// Original Content passed in to the call.
///
- public string Content => _content;
+ public string Content { get; } = initialContent;
///
/// Gets a value indicating if the content has a suggestion.
@@ -26,7 +29,7 @@ public class XamlRenderResultContext
///
/// Content modified by pre-parser helpers with any missing xmlns elements.
///
- public string SuggestedContent { get; internal set; }
+ public string SuggestedContent { get; internal set; } = initialContent;
///
/// Content that represents the actually rendered .
@@ -34,7 +37,7 @@ public class XamlRenderResultContext
/// which add missing elements or inject helpers for images, data context, and binding debugging.
/// It is mainly intended for debugging the itself.
///
- public string RenderedContent { get; internal set; }
+ public string RenderedContent { get; internal set; } = initialContent;
///
/// Element rendered by or null if rendering was unsuccessful.
@@ -99,7 +102,7 @@ public class XamlRenderResultContext
///
/// Gets the list of Errors found if was unsuccessful.
///
- public IList Errors { get; internal set; } = new List();
+ public IList Errors { get; internal set; } = [];
///
/// Gets the list of Bindings found when is turned on. Cleared and Populated after a call to .
@@ -110,15 +113,4 @@ public class XamlRenderResultContext
/// Gets the list of known Namespaces found on the document.
///
public XmlnsNamespace[] DetectedNamespaces { get; internal set; }
-
- ///
- /// Create a new XamlRenderResultContext for the given initial content.
- ///
- /// Initial string passed to render.
- public XamlRenderResultContext(string initialContent)
- {
- _content = initialContent;
- SuggestedContent = initialContent;
- RenderedContent = initialContent;
- }
}
diff --git a/XamlStudio.Toolkit/Models/XamlRenderSettings.cs b/XamlStudio.Toolkit/Models/XamlRenderSettings.cs
index 119946b..15bbbab 100644
--- a/XamlStudio.Toolkit/Models/XamlRenderSettings.cs
+++ b/XamlStudio.Toolkit/Models/XamlRenderSettings.cs
@@ -12,7 +12,7 @@ namespace XamlStudio.Toolkit.Models;
///
public class XamlRenderSettings
{
- private HashSet _namespaces = new HashSet();
+ private HashSet _namespaces = [];
///
/// Gets the dictionary of known namespaces to automatically try and add if missing in given content to Render.
///
diff --git a/XamlStudio.Toolkit/Parsers/BindingParser.cs b/XamlStudio.Toolkit/Parsers/BindingParser.cs
index b7c23cb..4dc85bb 100644
--- a/XamlStudio.Toolkit/Parsers/BindingParser.cs
+++ b/XamlStudio.Toolkit/Parsers/BindingParser.cs
@@ -24,7 +24,7 @@ public static class BindingParser
// Put together our possible Property = Value clause
private static string BindingPropertiesPattern = string.Format("({0}\\s*=\\s*{1})+", regProp, regValue);
- private static Regex BindingPropertyExtractor = new Regex(BindingPropertiesPattern, RegexOptions.Compiled | RegexOptions.Singleline);
+ private static Regex BindingPropertyExtractor = new(BindingPropertiesPattern, RegexOptions.Compiled | RegexOptions.Singleline);
private static Dictionary PropertyTable =
typeof(BindingValue).GetProperties()
diff --git a/XamlStudio.Toolkit/Services/AppAssemblyInfo.cs b/XamlStudio.Toolkit/Services/AppAssemblyInfo.cs
index c2b957d..7bd66e5 100644
--- a/XamlStudio.Toolkit/Services/AppAssemblyInfo.cs
+++ b/XamlStudio.Toolkit/Services/AppAssemblyInfo.cs
@@ -19,7 +19,7 @@ public class AppAssemblyInfo
{
public static AppAssemblyInfo Instance => Singleton.Instance;
- private readonly AsyncLock _mutex = new AsyncLock();
+ private readonly AsyncLock _mutex = new();
public bool IsLoaded { get; private set; }
public IReadOnlyList LoadedAssemblies { get; private set; }
@@ -50,10 +50,11 @@ private async Task LoadAssembliesAsync(Assembly[] extraAssemblies = null)
// Add any provided assemblies
// Current workaround for Microsoft.UI.Xaml and this limitation:
// https://social.msdn.microsoft.com/Forums/en-US/a78fdd8e-a108-4279-9e6b-6c87cd0a0f0f/assemblyload-of-winmd-file-possible
- var assemblies = new HashSet(extraAssemblies ?? Enumerable.Empty());
-
- // Add Windows Assembly
- assemblies.Add(typeof(FrameworkElement).GetTypeInfo().Assembly); // Windows.UI.Xaml
+ var assemblies = new HashSet(extraAssemblies ?? Enumerable.Empty())
+ {
+ // Add Windows Assembly
+ typeof(FrameworkElement).GetTypeInfo().Assembly // Windows.UI.Xaml
+ };
// Add Other Assemblies (Debug Only)
var files = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFilesAsync();
@@ -102,7 +103,7 @@ private void MapTypes()
}
else if (!mapping.ContainsKey(type.Namespace))
{
- mapping[type.Namespace] = new List();
+ mapping[type.Namespace] = [];
}
mapping[type.Namespace].Add(type);
diff --git a/XamlStudio.Toolkit/Services/IdGenerator.cs b/XamlStudio.Toolkit/Services/IdGenerator.cs
index e610d86..12bab37 100644
--- a/XamlStudio.Toolkit/Services/IdGenerator.cs
+++ b/XamlStudio.Toolkit/Services/IdGenerator.cs
@@ -11,7 +11,7 @@ namespace XamlStudio.Toolkit.Services;
///
public static class IdGenerator
{
- public static object lockable = new object();
+ public static object lockable = new();
public static int _count = 1;
public static int Next()
diff --git a/XamlStudio.Toolkit/Services/XamlAutocompleteService/XamlAutocompleteService.cs b/XamlStudio.Toolkit/Services/XamlAutocompleteService/XamlAutocompleteService.cs
index b3512ea..c327a17 100644
--- a/XamlStudio.Toolkit/Services/XamlAutocompleteService/XamlAutocompleteService.cs
+++ b/XamlStudio.Toolkit/Services/XamlAutocompleteService/XamlAutocompleteService.cs
@@ -20,7 +20,7 @@ public class XamlAutocompleteService
private const string RegexPattern_XmlnsNamespace = @"xmlns(|:(?[\w-]*))=""(?.*)""";
- private static Regex _namespaceSearcher = new Regex(RegexPattern_XmlnsNamespace, RegexOptions.Compiled);
+ private static Regex _namespaceSearcher = new(RegexPattern_XmlnsNamespace, RegexOptions.Compiled);
public IEnumerable GetNamespaces(string content)
{
diff --git a/XamlStudio.Toolkit/Services/XamlAutocompleteService/XamlLanguageProvider.cs b/XamlStudio.Toolkit/Services/XamlAutocompleteService/XamlLanguageProvider.cs
index c08cca5..8ab9b0d 100644
--- a/XamlStudio.Toolkit/Services/XamlAutocompleteService/XamlLanguageProvider.cs
+++ b/XamlStudio.Toolkit/Services/XamlAutocompleteService/XamlLanguageProvider.cs
@@ -32,82 +32,77 @@ public class XamlLanguageProvider : CompletionItemProvider
public string[] TriggerCharacters => new string[] { ElementTrigger, CloseElementTrigger, NamespaceTrigger, AttributeValueTrigger };
public IAsyncOperation ProvideCompletionItemsAsync(IModel model, IPosition position, CompletionContext context)
- {
- return AsyncInfo.Run(async delegate (CancellationToken cancelationToken)
- {
- var items = new List();
+ => AsyncInfo.Run(async delegate (CancellationToken cancelationToken)
+ {
+ var items = new List();
- // get editor content before the pointer
- var text = await model.GetValueAsync();
+ // get editor content before the pointer
+ var text = await model.GetValueAsync();
- // TODO: Should try and coordinate where we need this model between render, document, and here.
- // LINK: Document.xaml.cs:UpdateBreadcrumbs
- var _xmlRoot = Parser.ParseText(text);
+ // TODO: Should try and coordinate where we need this model between render, document, and here.
+ // LINK: Document.xaml.cs:UpdateBreadcrumbs
+ var _xmlRoot = Parser.ParseText(text);
- var index = text.GetCharacterIndex((int)position.LineNumber, (int)position.Column);
+ var index = text.GetCharacterIndex((int)position.LineNumber, (int)position.Column);
- if (index == -1)
- {
- return null;
- }
+ if (index == -1)
+ {
+ return null;
+ }
- var raw_node = _xmlRoot.FindNode(index + 1);
+ var raw_node = _xmlRoot.FindNode(index + 1);
- var parentTagName = raw_node?.ParentElement?.Name;
+ var parentTagName = raw_node?.ParentElement?.Name;
- // get list of assemblies
- var namespaces = KnownNamespaces.Concat(XamlAutocompleteService.Instance.GetNamespaces(await model.GetValueAsync()));
+ // get list of assemblies
+ var namespaces = KnownNamespaces.Concat(XamlAutocompleteService.Instance.GetNamespaces(await model.GetValueAsync()));
- if (context.TriggerCharacter == CloseElementTrigger)
- {
- if (index >= 1 && text[index - 1] == '<')
+ if (context.TriggerCharacter == CloseElementTrigger)
{
- // Only show suggestion if we're starting a close tag.
- items.Add(new CompletionItem(parentTagName, CompletionItemKind.Class));
+ if (index >= 1 && text[index - 1] == '<')
+ {
+ // Only show suggestion if we're starting a close tag.
+ items.Add(new CompletionItem(parentTagName, CompletionItemKind.Class));
+ }
}
- }
- else if (context.TriggerCharacter == ElementTrigger)
- {
- // TODO: Add hint of containing element (ResourceDictionary,
- XamlAutocompleteService.Instance.AddDefaultSuggestions(items, KnownNamespaces);
- }
- else if (context.TriggerCharacter == NamespaceTrigger)
- {
- // TODO: Don't show these if in first tag... show suggestions from known namespaces list... (not accessible here, in App :()
- if (!string.IsNullOrWhiteSpace(parentTagName))
+ else if (context.TriggerCharacter == ElementTrigger)
{
- XamlAutocompleteService.Instance.AddNamespaceSuggestions(items, parentTagName.Trim(':'), KnownNamespaces);
+ // TODO: Add hint of containing element (ResourceDictionary,
+ XamlAutocompleteService.Instance.AddDefaultSuggestions(items, KnownNamespaces);
}
- }
- else if (context.TriggerCharacter == AttributeValueTrigger)
- {
- if (!string.IsNullOrWhiteSpace(parentTagName))
+ else if (context.TriggerCharacter == NamespaceTrigger)
+ {
+ // TODO: Don't show these if in first tag... show suggestions from known namespaces list... (not accessible here, in App :()
+ if (!string.IsNullOrWhiteSpace(parentTagName))
+ {
+ XamlAutocompleteService.Instance.AddNamespaceSuggestions(items, parentTagName.Trim(':'), KnownNamespaces);
+ }
+ }
+ else if (context.TriggerCharacter == AttributeValueTrigger)
{
- var attribute = raw_node.FirstAncestorOrSelf();
+ if (!string.IsNullOrWhiteSpace(parentTagName))
+ {
+ var attribute = raw_node.FirstAncestorOrSelf();
- XamlAutocompleteService.Instance.AddValueSuggestions(items, parentTagName, attribute?.Name);
+ XamlAutocompleteService.Instance.AddValueSuggestions(items, parentTagName, attribute?.Name);
+ }
}
- }
- else
- {
- if (!string.IsNullOrWhiteSpace(parentTagName))
+ else
{
- var attribute = raw_node.FirstAncestorOrSelf();
+ if (!string.IsNullOrWhiteSpace(parentTagName))
+ {
+ var attribute = raw_node.FirstAncestorOrSelf();
- // TODO: Filter out already used properties...
- XamlAutocompleteService.Instance.AddPropertySuggestions(items, parentTagName);
+ // TODO: Filter out already used properties...
+ XamlAutocompleteService.Instance.AddPropertySuggestions(items, parentTagName);
+ }
}
- }
- return new CompletionList()
- {
- Items = items
- };
- });
- }
-
- public IAsyncOperation ResolveCompletionItemAsync(CompletionItem item)
- {
- throw new NotImplementedException();
- }
+ return new CompletionList()
+ {
+ Items = items
+ };
+ });
+
+ public IAsyncOperation ResolveCompletionItemAsync(CompletionItem item) => throw new NotImplementedException();
}
diff --git a/XamlStudio.Toolkit/Services/XamlBindingWrapperManager.cs b/XamlStudio.Toolkit/Services/XamlBindingWrapperManager.cs
index 21460bd..f5bf6e2 100644
--- a/XamlStudio.Toolkit/Services/XamlBindingWrapperManager.cs
+++ b/XamlStudio.Toolkit/Services/XamlBindingWrapperManager.cs
@@ -14,15 +14,15 @@ namespace XamlStudio.Toolkit.Services;
///
public class XamlBindingWrapperManager : Dictionary
{
- private readonly Dictionary _renderers = new Dictionary();
- private readonly Dictionary> _tracker = new Dictionary>();
+ private readonly Dictionary _renderers = [];
+ private readonly Dictionary> _tracker = [];
public static XamlBindingWrapperManager Instance => Singleton.Instance;
public void Register(int id, XamlRenderService service)
{
this._renderers.Add(id, service);
- this._tracker[id] = new List();
+ this._tracker[id] = [];
}
public void AddNewBinding(int serviceId, XamlBindingInfo binding)
@@ -51,6 +51,6 @@ public void Clear(int serviceId)
this.Remove(binding);
}
- this._tracker[serviceId] = new List();
+ this._tracker[serviceId] = [];
}
}
diff --git a/XamlStudio.Toolkit/Services/XamlRenderService/XamlRenderService.ParseBinding.cs b/XamlStudio.Toolkit/Services/XamlRenderService/XamlRenderService.ParseBinding.cs
index 2c2b63f..a71235a 100644
--- a/XamlStudio.Toolkit/Services/XamlRenderService/XamlRenderService.ParseBinding.cs
+++ b/XamlStudio.Toolkit/Services/XamlRenderService/XamlRenderService.ParseBinding.cs
@@ -14,8 +14,8 @@ public partial class XamlRenderService
{
private const string BindingSearcherPattern = "([\"']){\\s*(?(?:Binding)).*?}\\1"; //"([\"']){\\s*(?(?:Binding)|(?:x:Bind)).*?}\\1"; // \1 matches initial single or double quote used in first capturing group.
private const string BindingPropertiesPattern = "((?(?:BindBack)|(?:Converter)|(?:ConverterLanguage)|(?:ConverterParameter)|(?:ElementName)|(?:FallbackValue)|(?:Mode)|(?:Path)|(?:RelativeSource)|(?:Source)|(?:TargetNullValue)|(?:UpdateSourceTrigger))\\s*=\\s*(?.*?(?({)({(?>{(?)|}(?<-DEPTH>)|.?)*(?(DEPTH)(?!))}(?=[,}]))|(.*?(?=[,}])))))+";
- private static Regex BindingSearcher = new Regex(BindingSearcherPattern, RegexOptions.Compiled | RegexOptions.Singleline);
- private static Regex BindingPropertyExtractor = new Regex(BindingPropertiesPattern, RegexOptions.Compiled | RegexOptions.Singleline);
+ private static Regex BindingSearcher = new(BindingSearcherPattern, RegexOptions.Compiled | RegexOptions.Singleline);
+ private static Regex BindingPropertyExtractor = new(BindingPropertiesPattern, RegexOptions.Compiled | RegexOptions.Singleline);
///
/// Replace Binding Expressions with equivalents but intercepted by our own converter for additional logic/redirection.
diff --git a/XamlStudio.Toolkit/Services/XamlRenderService/XamlRenderService.ParsePre.cs b/XamlStudio.Toolkit/Services/XamlRenderService/XamlRenderService.ParsePre.cs
index fbe194e..15f6a3a 100644
--- a/XamlStudio.Toolkit/Services/XamlRenderService/XamlRenderService.ParsePre.cs
+++ b/XamlStudio.Toolkit/Services/XamlRenderService/XamlRenderService.ParsePre.cs
@@ -20,8 +20,8 @@ public partial class XamlRenderService
private const string RegexPattern_FirstTagAfterComment = @"(?!(<\?|";
private const string RegexPattern_ElementName = "<((?\\w+):)?(?\\w+)";
- private static Regex _initialTagSearcher = new Regex(RegexPattern_FirstTagAfterComment, RegexOptions.Compiled);
- private static Regex _elementNameSearcher = new Regex(RegexPattern_ElementName, RegexOptions.Compiled);
+ private static Regex _initialTagSearcher = new(RegexPattern_FirstTagAfterComment, RegexOptions.Compiled);
+ private static Regex _elementNameSearcher = new(RegexPattern_ElementName, RegexOptions.Compiled);
///
/// Returns the first initial element tag after a comment.
@@ -147,11 +147,9 @@ internal static void PreProcessXmlns(ref XamlRenderResultContext context, ref Xa
context.RenderedContent = content;
}
- public static Type GetTypeFromName(string typename)
- {
+ public static Type GetTypeFromName(string typename) =>
// TODO: Do we need to worry about conflicting names across assemblies and pass in the namespace to this function?
- return AppAssemblyInfo.Instance.KnownTypes.FirstOrDefault(t => t.Name == typename);
- }
+ AppAssemblyInfo.Instance.KnownTypes.FirstOrDefault(t => t.Name == typename);
internal static bool IsFrameworkElement(Type type)
{
diff --git a/XamlStudio.Toolkit/Services/XamlRenderService/XamlRenderService.cs b/XamlStudio.Toolkit/Services/XamlRenderService/XamlRenderService.cs
index c449f16..19b4394 100644
--- a/XamlStudio.Toolkit/Services/XamlRenderService/XamlRenderService.cs
+++ b/XamlStudio.Toolkit/Services/XamlRenderService/XamlRenderService.cs
@@ -39,17 +39,13 @@ public XamlRenderService()
public async Task RenderAsync(string content, XamlRenderSettings settings = null)
{
// Use default settings if none provided.
- if (settings == null)
- {
- settings = new XamlRenderSettings();
- }
+ settings ??= new XamlRenderSettings();
// Remove previous Binding Tracking
XamlBindingWrapperManager.Instance.Clear(this.Id);
// Hold all outcomes of this process in an object we'll return when done.
- var result = new XamlRenderResultContext(content);
- result.Bindings = Enumerable.Empty();
+ var result = new XamlRenderResultContext(content) { Bindings = Enumerable.Empty() };
// Load extra Metadata about other available types.
if (!AppAssemblyInfo.Instance.IsLoaded)
@@ -231,10 +227,7 @@ public async Task RenderAsync(string content, XamlRende
// Merge App.xaml resources into our root element's resources.
if (result.Element is FrameworkElement rootFwe)
{
- if (rootFwe.Resources == null)
- {
- rootFwe.Resources = new ResourceDictionary();
- }
+ rootFwe.Resources ??= [];
// Note: This needs to happen before element is added to the Visual Tree!
// IMPORTANT!!! This doesn't work for all styling (weirdly) while under a debugger... need to file a WinUI bug...
rootFwe.Resources.MergedDictionaries.Add(appResources);
diff --git a/XamlStudio.Toolkit/Services/XamlXmlTreeCoordinator.cs b/XamlStudio.Toolkit/Services/XamlXmlTreeCoordinator.cs
index 07351d7..d46ea93 100644
--- a/XamlStudio.Toolkit/Services/XamlXmlTreeCoordinator.cs
+++ b/XamlStudio.Toolkit/Services/XamlXmlTreeCoordinator.cs
@@ -274,7 +274,7 @@ public class XamlXmlTreeCoordinator
}
};
- private BidirectionalDictionary _treeMapper = new();
+ private BidirectionalDictionary _treeMapper = [];
public int Count => _treeMapper.Count;
@@ -286,15 +286,9 @@ public XamlXmlTreeCoordinator()
public IReadOnlyCollection GetXmlElements() => _treeMapper.Keys;
- public bool TryGetVisualElement(IXmlElementSyntax node, out DependencyObject element)
- {
- return _treeMapper.TryGetValue(node, out element);
- }
+ public bool TryGetVisualElement(IXmlElementSyntax node, out DependencyObject element) => _treeMapper.TryGetValue(node, out element);
- public bool TryGetXmlElement(DependencyObject element, out IXmlElementSyntax node)
- {
- return _treeMapper.Inverse.TryGetValue(element, out node);
- }
+ public bool TryGetXmlElement(DependencyObject element, out IXmlElementSyntax node) => _treeMapper.Inverse.TryGetValue(element, out node);
//// TODO: Not sure how long this takes, so maybe wrap in a Task? Though does require UIThread...hmmm
public void Initialize(XmlDocumentSyntax docRoot, DependencyObject visualRoot)
@@ -351,10 +345,10 @@ private DependencyObject FindMatchingUIElement(DependencyObject visualNode, IXml
// TODO: Think about or time against a DFS instead to see which is more efficient, not sure if case-by-case.
// Or maybe if we use DFS with a limited depth, as theoretically we shouldn't have to dig far if we're snapping above
Queue queue = new();
- HashSet explored = new()
- {
+ HashSet explored =
+ [
visualNode
- };
+ ];
queue.Enqueue(visualNode);
while (queue.Count > 0)
{
diff --git a/XamlStudio/Activation/ActivationHandler.cs b/XamlStudio/Activation/ActivationHandler.cs
index ebdce5d..51943d2 100644
--- a/XamlStudio/Activation/ActivationHandler.cs
+++ b/XamlStudio/Activation/ActivationHandler.cs
@@ -19,18 +19,9 @@ internal abstract class ActivationHandler : ActivationHandler
{
protected abstract Task HandleInternalAsync(T args);
- public override async Task HandleAsync(object args)
- {
- await HandleInternalAsync(args as T);
- }
-
- public override bool CanHandle(object args)
- {
- return args is T && CanHandleInternal(args as T);
- }
-
- protected virtual bool CanHandleInternal(T args)
- {
- return true;
- }
+ public override async Task HandleAsync(object args) => await HandleInternalAsync(args as T);
+
+ public override bool CanHandle(object args) => args is T t && CanHandleInternal(t);
+
+ protected virtual bool CanHandleInternal(T args) => true;
}
diff --git a/XamlStudio/Activation/DefaultLaunchActivationHandler.cs b/XamlStudio/Activation/DefaultLaunchActivationHandler.cs
index 97629b7..605503f 100644
--- a/XamlStudio/Activation/DefaultLaunchActivationHandler.cs
+++ b/XamlStudio/Activation/DefaultLaunchActivationHandler.cs
@@ -29,9 +29,7 @@ protected override async Task HandleInternalAsync(LaunchActivatedEventArgs args)
await Task.CompletedTask;
}
- protected override bool CanHandleInternal(LaunchActivatedEventArgs args)
- {
+ protected override bool CanHandleInternal(LaunchActivatedEventArgs args) =>
// None of the ActivationHandlers has handled the app activation
- return NavigationService.Frame.Content == null;
- }
+ NavigationService.Frame.Content == null;
}
diff --git a/XamlStudio/Activation/FileActivationHandler.cs b/XamlStudio/Activation/FileActivationHandler.cs
index f69a91e..a4bcb14 100644
--- a/XamlStudio/Activation/FileActivationHandler.cs
+++ b/XamlStudio/Activation/FileActivationHandler.cs
@@ -38,10 +38,8 @@ protected override async Task HandleInternalAsync(FileActivatedEventArgs args)
await Task.CompletedTask;
}
- protected override bool CanHandleInternal(FileActivatedEventArgs args)
- {
+ protected override bool CanHandleInternal(FileActivatedEventArgs args) =>
// If your app has multiple handlers of FileActivationEventArgs
// use this method to determine which to use. (possibly checking args.Files)
- return true;
- }
+ true;
}
diff --git a/XamlStudio/Activation/SchemeActivationHandler.cs b/XamlStudio/Activation/SchemeActivationHandler.cs
index 20349fa..dda693c 100644
--- a/XamlStudio/Activation/SchemeActivationHandler.cs
+++ b/XamlStudio/Activation/SchemeActivationHandler.cs
@@ -51,10 +51,8 @@ protected override async Task HandleInternalAsync(ProtocolActivatedEventArgs arg
await Task.CompletedTask;
}
- protected override bool CanHandleInternal(ProtocolActivatedEventArgs args)
- {
+ protected override bool CanHandleInternal(ProtocolActivatedEventArgs args) =>
// If your app has multiple handlers of ProtocolActivationEventArgs
// use this method to determine which to use. (possibly checking args.Uri.Scheme)
- return true;
- }
+ true;
}
diff --git a/XamlStudio/Activation/WebToAppLinkActivationHandler.cs b/XamlStudio/Activation/WebToAppLinkActivationHandler.cs
index d4328aa..7d23c18 100644
--- a/XamlStudio/Activation/WebToAppLinkActivationHandler.cs
+++ b/XamlStudio/Activation/WebToAppLinkActivationHandler.cs
@@ -40,8 +40,5 @@ protected override async Task HandleInternalAsync(ProtocolActivatedEventArgs arg
await Task.CompletedTask;
}
- protected override bool CanHandleInternal(ProtocolActivatedEventArgs args)
- {
- return args?.Uri?.Host == Host;
- }
+ protected override bool CanHandleInternal(ProtocolActivatedEventArgs args) => args?.Uri?.Host == Host;
}
diff --git a/XamlStudio/App.xaml.cs b/XamlStudio/App.xaml.cs
index f1f9323..1b422ec 100644
--- a/XamlStudio/App.xaml.cs
+++ b/XamlStudio/App.xaml.cs
@@ -25,10 +25,7 @@ namespace XamlStudio;
public sealed partial class App : Application
{
private Lazy _activationService;
- private ActivationService ActivationService
- {
- get { return _activationService.Value; }
- }
+ private ActivationService ActivationService => _activationService.Value;
public App()
{
@@ -77,10 +74,7 @@ protected override async void OnFileActivated(FileActivatedEventArgs args)
await ActivationService.ActivateAsync(args);
}
- private ActivationService CreateActivationService()
- {
- return new ActivationService(this, typeof(Views.MainPage));
- }
+ private ActivationService CreateActivationService() => new ActivationService(this, typeof(Views.MainPage));
private async void App_EnteredBackground(object sender, EnteredBackgroundEventArgs e)
{
@@ -116,9 +110,7 @@ private async void App_Suspending(object sender, SuspendingEventArgs e)
/// Handles the event of extended execution being revoked.
///
private void App_ExtendedExecutionRevoked(object sender, ExtendedExecutionRevokedEventArgs args)
- {
- AppLoggerService.LogInfo($"The request to ExtendedExecutionSession was revoked with reason {args.Reason}");
- }
+ => AppLoggerService.LogInfo($"The request to ExtendedExecutionSession was revoked with reason {args.Reason}");
///
/// Invoked when application execution is being resummed.
diff --git a/XamlStudio/Controls/AppFontIcon.cs b/XamlStudio/Controls/AppFontIcon.cs
index 4c2cdb9..9337a86 100644
--- a/XamlStudio/Controls/AppFontIcon.cs
+++ b/XamlStudio/Controls/AppFontIcon.cs
@@ -16,10 +16,7 @@ public class AppFontIcon : FontIcon
/// call ApplyTemplate. In simplest terms, this means the method is called just before a UI element
/// displays in your app. Override this method to influence the default post-template logic of a class.
///
- protected override void OnApplyTemplate()
- {
- base.OnApplyTemplate();
- }
+ protected override void OnApplyTemplate() => base.OnApplyTemplate();
#region IconName (Dependency Property)
@@ -148,15 +145,12 @@ public static class IconGlyphValues
///
/// Tries to get a unicode value out of the given icon name.
///
- public static string GetIcon(IconGlyphNames icon)
- {
- return IconMapping.TryGetValue(icon, out string value) ? value : string.Empty;
- }
+ public static string GetIcon(IconGlyphNames icon) => IconMapping.TryGetValue(icon, out string value) ? value : string.Empty;
///
/// Maps the icon names into unicode values.
///
- private static readonly Dictionary IconMapping = new Dictionary()
+ private static readonly Dictionary IconMapping = new()
{
{IconGlyphNames.Search, "\uE721"},
{IconGlyphNames.Work, "\uE821"},
@@ -199,16 +193,14 @@ public static class IconSizeValues
///
/// Tries to get a numercal value out of the indicated name.
///
- public static double GetIconSize(IconContexts sizeName)
- {
+ public static double GetIconSize(IconContexts sizeName) =>
// Default Value is 16 based on ContentControlFontSize from ThemeResources
- return SizeMapping.TryGetValue(sizeName, out double value) ? value : 16.0;
- }
+ SizeMapping.TryGetValue(sizeName, out double value) ? value : 16.0;
///
/// Maps the Size names to numerical values.
///
- private static readonly Dictionary SizeMapping = new Dictionary()
+ private static readonly Dictionary SizeMapping = new()
{
{IconContexts.Smaller, 10.0 },
{IconContexts.Small, 12.0 },
diff --git a/XamlStudio/Helpers/EnumValueExtension.cs b/XamlStudio/Helpers/EnumValueExtension.cs
index a303493..0bdac94 100644
--- a/XamlStudio/Helpers/EnumValueExtension.cs
+++ b/XamlStudio/Helpers/EnumValueExtension.cs
@@ -15,8 +15,5 @@ public class EnumValueExtension : MarkupExtension
public string Member { get; set; }
- protected override object ProvideValue()
- {
- return Enum.Parse(Type, Member);
- }
+ protected override object ProvideValue() => Enum.Parse(Type, Member);
}
diff --git a/XamlStudio/Helpers/Json.cs b/XamlStudio/Helpers/Json.cs
index 3d17f47..d16feea 100644
--- a/XamlStudio/Helpers/Json.cs
+++ b/XamlStudio/Helpers/Json.cs
@@ -11,28 +11,22 @@ namespace XamlStudio.Helpers;
public static class Json
{
public static async Task ToObjectAsync(string value)
- {
- return await Task.Run(() =>
- {
- return JsonConvert.DeserializeObject(value);
- });
- }
+ => await Task.Run(() =>
+ {
+ return JsonConvert.DeserializeObject(value);
+ });
public static async Task ToObjectAsync(string value, Type type)
- {
- return await Task.Run(() =>
- {
- return JsonConvert.DeserializeObject(value, type);
- });
- }
+ => await Task.Run(() =>
+ {
+ return JsonConvert.DeserializeObject(value, type);
+ });
public static async Task StringifyAsync(object value)
- {
- return await Task.Run(() =>
- {
- return JsonConvert.SerializeObject(value);
- });
- }
+ => await Task.Run(() =>
+ {
+ return JsonConvert.SerializeObject(value);
+ });
public static object GetDefault(this Type type)
{
diff --git a/XamlStudio/Helpers/NavIconHelper.cs b/XamlStudio/Helpers/NavIconHelper.cs
index 273e1c8..c94e738 100644
--- a/XamlStudio/Helpers/NavIconHelper.cs
+++ b/XamlStudio/Helpers/NavIconHelper.cs
@@ -10,15 +10,9 @@ namespace XamlStudio.Helpers;
internal class NavItemIconHelper
{
- public static object GetSelectedIcon(NavigationViewItem obj)
- {
- return obj.GetValue(SelectedIconProperty);
- }
+ public static object GetSelectedIcon(NavigationViewItem obj) => obj.GetValue(SelectedIconProperty);
- public static void SetSelectedIcon(NavigationViewItem obj, object value)
- {
- obj.SetValue(SelectedIconProperty, value);
- }
+ public static void SetSelectedIcon(NavigationViewItem obj, object value) => obj.SetValue(SelectedIconProperty, value);
public static readonly DependencyProperty SelectedIconProperty =
DependencyProperty.RegisterAttached("SelectedIcon", typeof(object), typeof(NavItemIconHelper), new PropertyMetadata(null));
@@ -27,18 +21,12 @@ public static void SetSelectedIcon(NavigationViewItem obj, object value)
/// Gets the value of for a
///
/// Returns a boolean indicating whether the notification dot should be shown.
- public static bool GetShowNotificationDot(NavigationViewItem obj)
- {
- return (bool)obj.GetValue(ShowNotificationDotProperty);
- }
+ public static bool GetShowNotificationDot(NavigationViewItem obj) => (bool)obj.GetValue(ShowNotificationDotProperty);
///
/// Sets on a
///
- public static void SetShowNotificationDot(NavigationViewItem obj, bool value)
- {
- obj.SetValue(ShowNotificationDotProperty, value);
- }
+ public static void SetShowNotificationDot(NavigationViewItem obj, bool value) => obj.SetValue(ShowNotificationDotProperty, value);
///
/// An attached property that sets whether or not a notification dot should be shown on an associated
@@ -50,18 +38,12 @@ public static void SetShowNotificationDot(NavigationViewItem obj, bool value)
/// Gets the value of for a
///
/// Returns the unselected icon as an object.
- public static object GetUnselectedIcon(NavigationViewItem obj)
- {
- return (object)obj.GetValue(UnselectedIconProperty);
- }
+ public static object GetUnselectedIcon(NavigationViewItem obj) => (object)obj.GetValue(UnselectedIconProperty);
///
/// Sets the value of for a
///
- public static void SetUnselectedIcon(NavigationViewItem obj, object value)
- {
- obj.SetValue(UnselectedIconProperty, value);
- }
+ public static void SetUnselectedIcon(NavigationViewItem obj, object value) => obj.SetValue(UnselectedIconProperty, value);
///
/// An attached property that sets the unselected icon on an associated
@@ -69,15 +51,9 @@ public static void SetUnselectedIcon(NavigationViewItem obj, object value)
public static readonly DependencyProperty UnselectedIconProperty =
DependencyProperty.RegisterAttached("UnselectedIcon", typeof(object), typeof(NavItemIconHelper), new PropertyMetadata(null));
- public static Visibility GetStaticIconVisibility(NavigationViewItem obj)
- {
- return (Visibility)obj.GetValue(StaticIconVisibilityProperty);
- }
+ public static Visibility GetStaticIconVisibility(NavigationViewItem obj) => (Visibility)obj.GetValue(StaticIconVisibilityProperty);
- public static void SetStaticIconVisibility(NavigationViewItem obj, Visibility value)
- {
- obj.SetValue(StaticIconVisibilityProperty, value);
- }
+ public static void SetStaticIconVisibility(NavigationViewItem obj, Visibility value) => obj.SetValue(StaticIconVisibilityProperty, value);
///
/// An attached property that sets the visibility of the static icon in the associated .
diff --git a/XamlStudio/Helpers/ResourceExtensions.cs b/XamlStudio/Helpers/ResourceExtensions.cs
index 8aea4c0..f464735 100644
--- a/XamlStudio/Helpers/ResourceExtensions.cs
+++ b/XamlStudio/Helpers/ResourceExtensions.cs
@@ -8,10 +8,7 @@ namespace XamlStudio.Helpers;
internal static class ResourceExtensions
{
- private static ResourceLoader _resLoader = new ResourceLoader();
+ private static ResourceLoader _resLoader = new();
- public static string GetLocalized(this string resourceKey)
- {
- return _resLoader.GetString(resourceKey);
- }
+ public static string GetLocalized(this string resourceKey) => _resLoader.GetString(resourceKey);
}
diff --git a/XamlStudio/Helpers/SettingsStorageExtensions.cs b/XamlStudio/Helpers/SettingsStorageExtensions.cs
index 5b3367d..dcf94e7 100644
--- a/XamlStudio/Helpers/SettingsStorageExtensions.cs
+++ b/XamlStudio/Helpers/SettingsStorageExtensions.cs
@@ -17,14 +17,11 @@ namespace XamlStudio.Helpers;
// https://docs.microsoft.com/windows/uwp/app-settings/store-and-retrieve-app-data
public static class SettingsStorageExtensions
{
- private static readonly AsyncLock _saveMutex = new AsyncLock();
+ private static readonly AsyncLock _saveMutex = new();
private const string FileExtension = ".json";
- public static bool IsRoamingStorageAvailable(this ApplicationData appData)
- {
- return appData.RoamingStorageQuota == 0;
- }
+ public static bool IsRoamingStorageAvailable(this ApplicationData appData) => appData.RoamingStorageQuota == 0;
public static async Task SaveAsync(this StorageFolder folder, string name, T content)
{
@@ -59,7 +56,7 @@ public static async Task ReadAsync(this StorageFolder folder, string name)
{
if (!File.Exists(Path.Combine(folder.Path, GetFileName(name))))
{
- return default(T);
+ return default;
}
var file = await folder.GetFileAsync($"{name}.json");
@@ -69,15 +66,9 @@ public static async Task ReadAsync(this StorageFolder folder, string name)
}
}
- public static async Task SaveAsync(this ApplicationDataContainer settings, string key, T value)
- {
- settings.SaveString(key, await Json.StringifyAsync(value));
- }
+ public static async Task SaveAsync(this ApplicationDataContainer settings, string key, T value) => settings.SaveString(key, await Json.StringifyAsync(value));
- public static void SaveString(this ApplicationDataContainer settings, string key, string value)
- {
- settings.Values[key] = value;
- }
+ public static void SaveString(this ApplicationDataContainer settings, string key, string value) => settings.Values[key] = value;
public static async Task ReadAsync(this ApplicationDataContainer settings, string key)
{
@@ -86,7 +77,7 @@ public static async Task ReadAsync(this ApplicationDataContainer settings,
return await Json.ToObjectAsync((string)obj);
}
- return default(T);
+ return default;
}
public static async Task ReadAsync(this ApplicationDataContainer settings, string key, Type type)
@@ -139,24 +130,17 @@ public static async Task ReadBytesAsync(this StorageFile file)
{
using (await _saveMutex.LockAsync())
{
- using (IRandomAccessStream stream = await file.OpenReadAsync())
- {
- using (var reader = new DataReader(stream.GetInputStreamAt(0)))
- {
- await reader.LoadAsync((uint)stream.Size);
- var bytes = new byte[stream.Size];
- reader.ReadBytes(bytes);
- return bytes;
- }
- }
+ using IRandomAccessStream stream = await file.OpenReadAsync();
+ using var reader = new DataReader(stream.GetInputStreamAt(0));
+ await reader.LoadAsync((uint)stream.Size);
+ var bytes = new byte[stream.Size];
+ reader.ReadBytes(bytes);
+ return bytes;
}
}
return null;
}
- private static string GetFileName(string name)
- {
- return string.Concat(name, FileExtension);
- }
+ private static string GetFileName(string name) => string.Concat(name, FileExtension);
}
diff --git a/XamlStudio/Models/DataContext.cs b/XamlStudio/Models/DataContext.cs
index 82f7492..c0db311 100644
--- a/XamlStudio/Models/DataContext.cs
+++ b/XamlStudio/Models/DataContext.cs
@@ -18,7 +18,7 @@ public sealed partial class DataContext : FileBackedDocument
[NotifyPropertyChangedFor(nameof(IsRemote))]
public partial string Uri { get; set; }
- public bool IsRemote { get { return !string.IsNullOrWhiteSpace(Uri); } }
+ public bool IsRemote => !string.IsNullOrWhiteSpace(Uri);
internal DataContext() : base() { }
diff --git a/XamlStudio/Models/FileBackedDocument.cs b/XamlStudio/Models/FileBackedDocument.cs
index e2ffc8e..c9d2597 100644
--- a/XamlStudio/Models/FileBackedDocument.cs
+++ b/XamlStudio/Models/FileBackedDocument.cs
@@ -44,7 +44,7 @@ public string Title
[NotifyPropertyChangedFor(nameof(Title))]
public partial bool HasChanged { get; set; }
- public bool CanSave { get { return BackingFile != null; } }
+ public bool CanSave => BackingFile != null;
public FileBackedDocument() { }
@@ -86,10 +86,7 @@ internal async Task RestoreFileAsync()
/// Save a file back to its backing location.
///
///
- public IAsyncOperation SaveAsync()
- {
- return SaveAsyncInternal().AsAsyncOperation();
- }
+ public IAsyncOperation SaveAsync() => SaveAsyncInternal().AsAsyncOperation();
private async Task SaveAsyncInternal()
{
@@ -119,10 +116,7 @@ private async Task SaveAsyncInternal()
///
/// New File Storage Location.
///
- public IAsyncOperation SaveAsAsync(StorageFile newFile)
- {
- return SaveAsAsyncInternal(newFile).AsAsyncOperation();
- }
+ public IAsyncOperation SaveAsAsync(StorageFile newFile) => SaveAsAsyncInternal(newFile).AsAsyncOperation();
private async Task SaveAsAsyncInternal(StorageFile newFile)
{
diff --git a/XamlStudio/Models/FolderLocation.cs b/XamlStudio/Models/FolderLocation.cs
index 6e8ca5b..540ffac 100644
--- a/XamlStudio/Models/FolderLocation.cs
+++ b/XamlStudio/Models/FolderLocation.cs
@@ -28,7 +28,7 @@ public partial class FolderLocation : ObservableObject
[NotifyPropertyChangedFor(nameof(IsInitialized))]
public partial StorageFolder BackingFolder { get; set; }
- public bool IsInitialized { get { return BackingFolder != null; } }
+ public bool IsInitialized => BackingFolder != null;
public FolderLocation() { }
diff --git a/XamlStudio/Models/ThirdPartyInfo.cs b/XamlStudio/Models/ThirdPartyInfo.cs
index 23b8a65..84e8fe1 100644
--- a/XamlStudio/Models/ThirdPartyInfo.cs
+++ b/XamlStudio/Models/ThirdPartyInfo.cs
@@ -23,7 +23,7 @@ public class ThirdPartyInfo
public string License { get; set; }
[JsonIgnore]
- public string LicenseAutomationName { get { return string.Format("License_Name_Format".GetLocalized(), License, Name); } }
+ public string LicenseAutomationName => string.Format("License_Name_Format".GetLocalized(), License, Name);
[JsonProperty("license_url")]
public string LicenseUrl { get; set; }
@@ -32,6 +32,6 @@ public class ThirdPartyInfo
public List LicenseText { get; set; }
[JsonIgnore]
- public string LicenseTextAutomationName { get { return string.Format("License_Text_Format".GetLocalized(), License, Name); } }
+ public string LicenseTextAutomationName => string.Format("License_Text_Format".GetLocalized(), License, Name);
}
diff --git a/XamlStudio/Models/WorkspaceWindow.cs b/XamlStudio/Models/WorkspaceWindow.cs
index 5a2b687..97242a9 100644
--- a/XamlStudio/Models/WorkspaceWindow.cs
+++ b/XamlStudio/Models/WorkspaceWindow.cs
@@ -27,9 +27,9 @@ public abstract partial class WorkspaceWindow : ObservableObject
[ObservableProperty]
public partial bool IsWorkspaceOpen { get; set; }
- public ObservableCollection WorkspaceFolders { get; private set; } = new();
+ public ObservableCollection WorkspaceFolders { get; private set; } = [];
- public ObservableCollection OpenFiles { get; private set; } = new();
+ public ObservableCollection OpenFiles { get; private set; } = [];
public WorkspaceWindow()
{
@@ -38,13 +38,11 @@ public WorkspaceWindow()
public abstract void Initialize();
- public static WorkspaceWindow GetDefaultWorkspace()
- {
+ public static WorkspaceWindow GetDefaultWorkspace() =>
//SettingsService.Instance.DefaultWorkspaceFolder
// Get Settings Folder
// IsWorkspaceOpen = false still.
throw new NotImplementedException();
- }
public void SetupWorkspace(StorageFolder folder)
{
@@ -76,8 +74,5 @@ partial void OnActiveFileChanged(XamlDocument oldValue, XamlDocument newValue)
ActiveFileChanged?.Invoke(this, newValue);
}
- partial void OnOpenActivityChanged(string value)
- {
- WeakReferenceMessenger.Default.Send(new(value));
- }
+ partial void OnOpenActivityChanged(string value) => WeakReferenceMessenger.Default.Send(new(value));
}
diff --git a/XamlStudio/Models/XamlDocument.cs b/XamlStudio/Models/XamlDocument.cs
index c3322f5..c116078 100644
--- a/XamlStudio/Models/XamlDocument.cs
+++ b/XamlStudio/Models/XamlDocument.cs
@@ -38,7 +38,7 @@ public sealed partial class XamlDocument : FileBackedDocument
public partial DocumentState State { get; set; } = new DocumentState();
[JsonIgnore]
- public string DisplayName { get { return BackingFile.DisplayName; } }
+ public string DisplayName => BackingFile.DisplayName;
internal XamlDocument()
{
@@ -55,15 +55,9 @@ public XamlDocument(StorageFile file) : base(file)
Initialize();
}
- private void Initialize()
- {
- Id = _id; // for first set unless deserialized
- }
+ private void Initialize() => Id = _id; // for first set unless deserialized
- public override string ToString()
- {
- return Title;
- }
+ public override string ToString() => Title;
///
/// Create a XamlDocument from an existing location.
diff --git a/XamlStudio/Services/ActivationService.cs b/XamlStudio/Services/ActivationService.cs
index 1cc85be..491074e 100644
--- a/XamlStudio/Services/ActivationService.cs
+++ b/XamlStudio/Services/ActivationService.cs
@@ -102,16 +102,11 @@ private IEnumerable GetActivationHandlers()
yield return Singleton.Instance;
}
- private bool IsInteractive(object args)
- {
- return args is IActivatedEventArgs;
- }
+ private bool IsInteractive(object args) => args is IActivatedEventArgs;
private void Frame_Navigated(object sender, NavigationEventArgs e)
- {
- SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = NavigationService.CanGoBack ?
+ => SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = NavigationService.CanGoBack ?
AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
- }
private void ActivationService_BackRequested(object sender, BackRequestedEventArgs e)
{
diff --git a/XamlStudio/Services/AppLoggerService.cs b/XamlStudio/Services/AppLoggerService.cs
index 8808711..5c64c86 100644
--- a/XamlStudio/Services/AppLoggerService.cs
+++ b/XamlStudio/Services/AppLoggerService.cs
@@ -17,7 +17,7 @@ namespace XamlStudio.Services;
///
public static class AppLoggerService
{
- private static readonly object locker = new object();
+ private static readonly object locker = new();
private static FileLogger fileLogger;
private static Guid sessionGuid;
@@ -38,10 +38,7 @@ public static void Initialize()
///
/// Application session identifier gets assigned every time the application gets activated.
///
- public static Guid SessionId
- {
- get { return sessionGuid; }
- }
+ public static Guid SessionId => sessionGuid;
///
/// Resets the session guid used by the app.
@@ -64,37 +61,25 @@ private static void LogAppVersion()
///
/// Causes the file logger to store all the messages it hasn't saved to disk.
///
- public static void FlushMessages()
- {
- Task.Run(() => fileLogger.FlushMessagesAsync(LogFileType.All)).Wait();
- }
+ public static void FlushMessages() => Task.Run(() => fileLogger.FlushMessagesAsync(LogFileType.All)).Wait();
///
/// Notifies the that the app is entering into suspension mode.
///
///
- public static Task OnSuspending()
- {
- return fileLogger.OnSuspending();
- }
+ public static Task OnSuspending() => fileLogger.OnSuspending();
///
/// NOtifies the that the app is entering into resume mode.
///
- public static void OnResuming()
- {
- fileLogger.OnResuming();
- }
+ public static void OnResuming() => fileLogger.OnResuming();
#region LogInfo
///
/// Logs an informational message.
///
///
- public static void LogInfo(string message)
- {
- fileLogger.Log(message, LoggingLevel.Information);
- }
+ public static void LogInfo(string message) => fileLogger.Log(message, LoggingLevel.Information);
///
/// Logs an informational message with format.
@@ -117,33 +102,22 @@ public static void LogInfo(string format, params object[] args)
/// Logs an error message with any acompanying exception.
///
private static void LogError(string caller, string message = null, Exception ex = null, LoggingLevel logLevel = LoggingLevel.Error)
- {
- fileLogger.Log($"AppError[{caller}]: {message ?? string.Empty} | Exception: {ex?.ToString()}", logLevel);
- }
+ => fileLogger.Log($"AppError[{caller}]: {message ?? string.Empty} | Exception: {ex?.ToString()}", logLevel);
///
/// Logs an exception only.
///
- public static void LogError(Exception e, [CallerMemberName] string caller = "")
- {
- LogError(caller: caller, message: null, ex: e);
- }
+ public static void LogError(Exception e, [CallerMemberName] string caller = "") => LogError(caller: caller, message: null, ex: e);
///
/// Logs an error message.
///
- public static void LogError(string message, [CallerMemberName] string caller = "")
- {
- LogError(caller: caller, message: message, ex: null);
- }
+ public static void LogError(string message, [CallerMemberName] string caller = "") => LogError(caller: caller, message: message, ex: null);
///
/// Logs an error message with exception details.
///
- public static void LogError(string message, Exception e, [CallerMemberName] string caller = "")
- {
- LogError(caller: caller, message: message, ex: e);
- }
+ public static void LogError(string message, Exception e, [CallerMemberName] string caller = "") => LogError(caller: caller, message: message, ex: e);
#endregion
diff --git a/XamlStudio/Services/LibraryService.cs b/XamlStudio/Services/LibraryService.cs
index d52dc66..4697d34 100644
--- a/XamlStudio/Services/LibraryService.cs
+++ b/XamlStudio/Services/LibraryService.cs
@@ -22,11 +22,11 @@ public class LibraryService
{
public static LibraryService Instance => Singleton.Instance;
- public ObservableCollection Libraries { get; private set; } = new ObservableCollection();
+ public ObservableCollection Libraries { get; private set; } = [];
public Dictionary LibrariesByNamespace { get; private set; }
- private readonly AsyncLock _initializeMutex = new AsyncLock();
+ private readonly AsyncLock _initializeMutex = new();
private bool _isInitialized = false;
public LibraryService()
diff --git a/XamlStudio/Services/Logging/FileLogger.cs b/XamlStudio/Services/Logging/FileLogger.cs
index 01c5a03..4cde47e 100644
--- a/XamlStudio/Services/Logging/FileLogger.cs
+++ b/XamlStudio/Services/Logging/FileLogger.cs
@@ -23,10 +23,10 @@ internal class FileLogger
private const string AppLogSchemaName = "XamlStudioLog";
private static bool isInitialized = false;
- private static object lockObject = new object();
- private static SemaphoreSlim flushSemaphore = new SemaphoreSlim(1);
+ private static object lockObject = new();
+ private static SemaphoreSlim flushSemaphore = new(1);
- private static readonly Lazy instance = new Lazy(
+ private static readonly Lazy instance = new(
() => new FileLogger(), LazyThreadSafetyMode.ExecutionAndPublication);
private ConcurrentQueue plainTextMessages;
@@ -47,10 +47,7 @@ internal class FileLogger
///
/// Returns the Singleton instance of .
///
- public static FileLogger Instance
- {
- get { return instance.Value; }
- }
+ public static FileLogger Instance => instance.Value;
private FileLogger()
{
@@ -96,18 +93,12 @@ private void InitSession()
///
/// Handles the event of the application entering into suspension.
///
- public Task OnSuspending()
- {
- return FlushMessagesAsync(LogFileType.All);
- }
+ public Task OnSuspending() => FlushMessagesAsync(LogFileType.All);
///
/// Triggers actions when the application resumes.
///
- public void OnResuming()
- {
- InitSession();
- }
+ public void OnResuming() => InitSession();
///
/// Flushes all the messages currently in processing to storage area.
@@ -143,10 +134,7 @@ public void Log(string message, LoggingLevel level = LoggingLevel.Information)
///
/// Handles the event when a log file is saved by
///
- private async void OnLogFileGenerated(IFileLoggingSession sender, LogFileGeneratedEventArgs args)
- {
- await MoveLogFileToLogFolder(args.File);
- }
+ private async void OnLogFileGenerated(IFileLoggingSession sender, LogFileGeneratedEventArgs args) => await MoveLogFileToLogFolder(args.File);
///
/// Closes the active log session and grabs the current log file to get it stored.
@@ -176,8 +164,7 @@ private async Task FlushTextFileMessagesAsync()
var messagesToFlush = new Queue();
while (true)
{
- string logMessage;
- if (plainTextMessages.TryDequeue(out logMessage))
+ if (plainTextMessages.TryDequeue(out string logMessage))
{
messagesToFlush.Enqueue(logMessage);
}
@@ -218,10 +205,7 @@ private async Task MoveLogFileToLogFolder(StorageFile logFile)
if (logFile != null)
{
StorageFolder targetFolder = logFolder;
- if (targetFolder == null)
- {
- targetFolder = await GetAppLogFolderAsync();
- }
+ targetFolder ??= await GetAppLogFolderAsync();
string logFileName = GenerateLogFileName(LogFileType.EventTraceLog, DateTime.Now);
await logFile.MoveAsync(targetFolder, logFileName, NameCollisionOption.GenerateUniqueName);
@@ -269,10 +253,7 @@ private async Task EnsureLogFileCreated()
///
public async Task GetAppLogFolderAsync()
{
- if (logFolder == null)
- {
- logFolder = await ApplicationData.Current.TemporaryFolder.CreateFolderAsync(logFolderName, CreationCollisionOption.OpenIfExists);
- }
+ logFolder ??= await ApplicationData.Current.TemporaryFolder.CreateFolderAsync(logFolderName, CreationCollisionOption.OpenIfExists);
return logFolder;
}
@@ -282,8 +263,7 @@ public async Task GetAppLogFolderAsync()
///
private string GetDateTimePath(DateTime date)
{
- string timeString = string.Empty;
-
+ string timeString;
try
{
timeString = date.ToString(new DateTimeFormatInfo().SortableDateTimePattern, CultureInfo.InvariantCulture);
@@ -313,17 +293,12 @@ private string GenerateLogFileName(LogFileType fileType, DateTime date)
///
/// Gets the file type extension to use based on the .
///
- private string GetFileExtension(LogFileType fileType)
+ private string GetFileExtension(LogFileType fileType) => fileType switch
{
- switch (fileType)
- {
- case LogFileType.EventTraceLog:
- return "etl";
- case LogFileType.Text:
- return "txt";
- }
- return "etl";
- }
+ LogFileType.EventTraceLog => "etl",
+ LogFileType.Text => "txt",
+ _ => "etl",
+ };
}
///
diff --git a/XamlStudio/Services/SettingsService.cs b/XamlStudio/Services/SettingsService.cs
index 1a69b89..4454f6c 100644
--- a/XamlStudio/Services/SettingsService.cs
+++ b/XamlStudio/Services/SettingsService.cs
@@ -21,7 +21,7 @@ public partial class SettingsService : ObservableObject
{
public static SettingsService Instance => Singleton.Instance;
- private readonly AsyncLock _initializeMutex = new AsyncLock();
+ private readonly AsyncLock _initializeMutex = new();
private bool _isInitialized = false;
public SettingsService()
@@ -85,13 +85,13 @@ public async Task InitializeAsync()
}
// Internal Cache
- private static Dictionary _settings = new Dictionary();
+ private static Dictionary _settings = [];
public T Get([CallerMemberName] string propertyName = null)
{
if (propertyName == null || !_settings.ContainsKey(propertyName))
{
- return default(T);
+ return default;
}
return (T)_settings[propertyName];
diff --git a/XamlStudio/Services/SuspendAndResumeService.cs b/XamlStudio/Services/SuspendAndResumeService.cs
index 086fb76..1b1c8da 100644
--- a/XamlStudio/Services/SuspendAndResumeService.cs
+++ b/XamlStudio/Services/SuspendAndResumeService.cs
@@ -17,7 +17,7 @@ namespace XamlStudio.Services;
internal class SuspendAndResumeService : ActivationHandler
{
- private readonly AsyncLock _suspendMutex = new AsyncLock();
+ private readonly AsyncLock _suspendMutex = new();
//// TODO WTS: For more information regarding the application lifecycle and how to handle suspend and resume, please see:
//// Documentation: https://docs.microsoft.com/windows/uwp/launch-resume/app-lifecycle
@@ -47,15 +47,9 @@ public async Task SaveStateAsync(string renderId = null)
}
}
- protected override async Task HandleInternalAsync(LaunchActivatedEventArgs args)
- {
- await RestoreStateAsync();
- }
+ protected override async Task HandleInternalAsync(LaunchActivatedEventArgs args) => await RestoreStateAsync();
- protected override bool CanHandleInternal(LaunchActivatedEventArgs args)
- {
- return true;
- }
+ protected override bool CanHandleInternal(LaunchActivatedEventArgs args) => true;
private async Task RestoreStateAsync()
{
diff --git a/XamlStudio/Services/ThemeSelectorService.cs b/XamlStudio/Services/ThemeSelectorService.cs
index bbbb97f..4054497 100644
--- a/XamlStudio/Services/ThemeSelectorService.cs
+++ b/XamlStudio/Services/ThemeSelectorService.cs
@@ -18,10 +18,7 @@ public static class ThemeSelectorService
public static ElementTheme Theme { get; set; } = ElementTheme.Default;
- public static async Task InitializeAsync()
- {
- Theme = await LoadThemeFromSettingsAsync();
- }
+ public static async Task InitializeAsync() => Theme = await LoadThemeFromSettingsAsync();
public static async Task SetThemeAsync(ElementTheme theme)
{
@@ -52,8 +49,5 @@ private static async Task LoadThemeFromSettingsAsync()
return cacheTheme;
}
- private static async Task SaveThemeInSettingsAsync(ElementTheme theme)
- {
- await ApplicationData.Current.LocalSettings.SaveAsync(SettingsKey, theme.ToString());
- }
+ private static async Task SaveThemeInSettingsAsync(ElementTheme theme) => await ApplicationData.Current.LocalSettings.SaveAsync(SettingsKey, theme.ToString());
}
diff --git a/XamlStudio/Services/ViewLifetimeControl.cs b/XamlStudio/Services/ViewLifetimeControl.cs
index 81ec385..6ff7324 100644
--- a/XamlStudio/Services/ViewLifetimeControl.cs
+++ b/XamlStudio/Services/ViewLifetimeControl.cs
@@ -72,10 +72,7 @@ private ViewLifetimeControl(CoreWindow newWindow)
RegisterForEvents();
}
- public static ViewLifetimeControl CreateForCurrentView()
- {
- return new ViewLifetimeControl(CoreWindow.GetForCurrentThread());
- }
+ public static ViewLifetimeControl CreateForCurrentView() => new ViewLifetimeControl(CoreWindow.GetForCurrentThread());
// Signals that the view is being interacted with by another view,
// so it shouldn't be closed even if it becomes "consolidated"
@@ -129,20 +126,11 @@ public int StopViewInUse()
return refCountCopy;
}
- private void RegisterForEvents()
- {
- ApplicationView.GetForCurrentView().Consolidated += ViewConsolidated;
- }
+ private void RegisterForEvents() => ApplicationView.GetForCurrentView().Consolidated += ViewConsolidated;
- private void UnregisterForEvents()
- {
- ApplicationView.GetForCurrentView().Consolidated -= ViewConsolidated;
- }
+ private void UnregisterForEvents() => ApplicationView.GetForCurrentView().Consolidated -= ViewConsolidated;
- private void ViewConsolidated(ApplicationView sender, ApplicationViewConsolidatedEventArgs e)
- {
- StopViewInUse();
- }
+ private void ViewConsolidated(ApplicationView sender, ApplicationViewConsolidatedEventArgs e) => StopViewInUse();
private void FinalizeRelease()
{
diff --git a/XamlStudio/Services/WindowManagerService.cs b/XamlStudio/Services/WindowManagerService.cs
index 0237d5d..62ac082 100644
--- a/XamlStudio/Services/WindowManagerService.cs
+++ b/XamlStudio/Services/WindowManagerService.cs
@@ -23,10 +23,10 @@ public class WindowManagerService
// https://docs.microsoft.com/windows/uwp/design/layout/show-multiple-views
private static WindowManagerService _current;
- public static WindowManagerService Current => _current ?? (_current = new WindowManagerService());
+ public static WindowManagerService Current => _current ??= new WindowManagerService();
// Contains all the opened secondary views.
- public ObservableCollection SecondaryViews { get; } = new ObservableCollection();
+ public ObservableCollection SecondaryViews { get; } = [];
public int MainViewId { get; private set; }
diff --git a/XamlStudio/ViewModels/DocumentViewModel.Methods.cs b/XamlStudio/ViewModels/DocumentViewModel.Methods.cs
index 8544a0b..c468992 100644
--- a/XamlStudio/ViewModels/DocumentViewModel.Methods.cs
+++ b/XamlStudio/ViewModels/DocumentViewModel.Methods.cs
@@ -29,7 +29,7 @@ namespace XamlStudio.ViewModels;
public partial class DocumentViewModel
{
- private readonly AsyncLock _renderMutex = new AsyncLock();
+ private readonly AsyncLock _renderMutex = new();
// TODO: Need to offset line with location in document?
/*private async void SelectiveRenderXaml(string content)
@@ -329,10 +329,7 @@ private void RotatePaneOrientation()
var orientation = Document.State.PreviewOrientation;
// If we're set to default, go grab that value to start from
- if (orientation == null)
- {
- orientation = Settings.DefaultPreviewPanePosition;
- }
+ orientation ??= Settings.DefaultPreviewPanePosition;
// Go to next enum value
orientation = (PaneOrientation)((((int)orientation.Value) + 1) % 4);
diff --git a/XamlStudio/ViewModels/DocumentViewModel.cs b/XamlStudio/ViewModels/DocumentViewModel.cs
index b266ffa..3f440aa 100644
--- a/XamlStudio/ViewModels/DocumentViewModel.cs
+++ b/XamlStudio/ViewModels/DocumentViewModel.cs
@@ -27,9 +27,7 @@ public partial class DocumentViewModel : ObservableObject
public partial XamlDocument Document { get; set; }
partial void OnDocumentChanged(XamlDocument value)
- {
- HasCompiled = false; // TODO: Reset compiled flag so we can re-render, probably want to cache elements previously rendered in XamlDocument, so we can re-add on document switch
- }
+ => HasCompiled = false; // TODO: Reset compiled flag so we can re-render, probably want to cache elements previously rendered in XamlDocument, so we can re-add on document switch
///
/// Selected Text in the Editor
@@ -49,7 +47,7 @@ partial void OnDocumentChanged(XamlDocument value)
[ObservableProperty]
public partial XamlXmlTreeCoordinator XamlCoordinator { get; set; } = new();
- private ObservableCollection _bindingHistory = new ObservableCollection();
+ private ObservableCollection _bindingHistory = [];
public AdvancedCollectionView BindingHistory
{
get
@@ -68,33 +66,33 @@ public AdvancedCollectionView BindingHistory
public ElementTheme ActualTheme { get; set; }
- public ObservableVector LineDecorations { get; private set; } = new ObservableVector();
+ public ObservableVector LineDecorations { get; private set; } = [];
- private static CssLineStyle _errorLineStyle = new CssLineStyle()
+ private static CssLineStyle _errorLineStyle = new()
{
BackgroundColor = new SolidColorBrush("#FFCA416A".ToColor())
};
- private static CssInlineStyle _errorStyle = new CssInlineStyle()
+ private static CssInlineStyle _errorStyle = new()
{
BackgroundColor = new SolidColorBrush("#FFCA416A".ToColor()),
ForegroundColor = new SolidColorBrush("#FFFFFFFF".ToColor()),
FontWeight = FontWeights.SemiBold
};
- private static CssInlineStyle _bindingStyleUnbound = new CssInlineStyle()
+ private static CssInlineStyle _bindingStyleUnbound = new()
{
BackgroundColor = new SolidColorBrush("#FFB4EBEF".ToColor()),
ForegroundColor = new SolidColorBrush("#FF333333".ToColor())
};
- private static CssInlineStyle _bindingStyleSuccess = new CssInlineStyle()
+ private static CssInlineStyle _bindingStyleSuccess = new()
{
BackgroundColor = new SolidColorBrush("#FFB9FEC1".ToColor()),
ForegroundColor = new SolidColorBrush("#FF333333".ToColor())
};
- private static CssInlineStyle _bindingStyleError = new CssInlineStyle()
+ private static CssInlineStyle _bindingStyleError = new()
{
BackgroundColor = new SolidColorBrush("#FFFFF689".ToColor()),
ForegroundColor = new SolidColorBrush("#FF663333".ToColor()),
diff --git a/XamlStudio/ViewModels/MainViewModel.Commands.Impl.cs b/XamlStudio/ViewModels/MainViewModel.Commands.Impl.cs
index c608e9b..5063ea1 100644
--- a/XamlStudio/ViewModels/MainViewModel.Commands.Impl.cs
+++ b/XamlStudio/ViewModels/MainViewModel.Commands.Impl.cs
@@ -21,7 +21,7 @@ namespace XamlStudio.ViewModels;
public partial class MainViewModel
{
- private readonly AsyncLock _openMutex = new AsyncLock();
+ private readonly AsyncLock _openMutex = new();
private void CloseWelcomeScreen()
{
@@ -64,9 +64,11 @@ private void DuplicateDocument()
[RelayCommand]
private async Task OpenDocument()
{
- var picker = new FileOpenPicker();
- picker.ViewMode = PickerViewMode.List;
- picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
+ var picker = new FileOpenPicker
+ {
+ ViewMode = PickerViewMode.List,
+ SuggestedStartLocation = PickerLocationId.DocumentsLibrary
+ };
picker.FileTypeFilter.Add(".xaml");
picker.FileTypeFilter.Add(".xml");
picker.FileTypeFilter.Add(".bind");
@@ -81,9 +83,7 @@ private async Task OpenDocument()
Documents.RemoveAt(0);
}*/
- OpenFile(file);
-
- CloseWelcomeScreen();
+ await OpenFile(file);
Analytics.TrackEvent("Document_Open");
}
@@ -113,10 +113,7 @@ public async void OpenFileFromWorkspace(StorageFile file, StorageFolder workspac
XamlDocument openDoc = OpenFiles.FirstOrDefault(f => f?.BackingFile?.Path == file.Path);
if (openDoc != null)
{
- if (openDoc.ParentFolder == null)
- {
- openDoc.ParentFolder = workspace;
- }
+ openDoc.ParentFolder ??= workspace;
ActiveFile = openDoc;
}
@@ -141,8 +138,10 @@ public async void OpenFileFromWorkspace(StorageFile file, StorageFolder workspac
[RelayCommand]
private async Task OpenFolderPicker()
{
- var picker = new FolderPicker();
- picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
+ var picker = new FolderPicker
+ {
+ SuggestedStartLocation = PickerLocationId.DocumentsLibrary
+ };
picker.FileTypeFilter.Add("*");
var folder = await picker.PickSingleFolderAsync();
@@ -261,10 +260,12 @@ private async Task SaveDocumentAs(XamlDocument document)
private async Task SaveFileDialog(string documentName)
{
- var savePicker = new FileSavePicker();
- savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
+ var savePicker = new FileSavePicker
+ {
+ SuggestedStartLocation = PickerLocationId.DocumentsLibrary
+ };
// Dropdown of file types the user can save the file as
- savePicker.FileTypeChoices.Add("eXtended Application Markup Language", new List() { ".xaml" });
+ savePicker.FileTypeChoices.Add("eXtended Application Markup Language", [".xaml"]);
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = documentName;
@@ -274,11 +275,11 @@ private async Task SaveFileDialog(string documentName)
[RelayCommand]
private async Task SaveDocument(XamlDocument document)
{
- StorageFile file = null;
// Ensure if we can restore the file if it wasn't available on load
await document.RestoreFileAsync();
+ StorageFile file;
// Save As
if (!document.CanSave)
{
diff --git a/XamlStudio/ViewModels/MainViewModel.cs b/XamlStudio/ViewModels/MainViewModel.cs
index d9b6fb3..cc2855e 100644
--- a/XamlStudio/ViewModels/MainViewModel.cs
+++ b/XamlStudio/ViewModels/MainViewModel.cs
@@ -19,15 +19,13 @@ public partial class MainViewModel : WorkspaceWindow
///
private int _untitledCount = 1;
- public Dictionary DocumentViewModels { get; } = new Dictionary();
+ public Dictionary DocumentViewModels { get; } = [];
[ObservableProperty]
public partial DocumentViewModel ActiveDocumentViewModel { get; set; }
partial void OnActiveDocumentViewModelChanged(DocumentViewModel oldValue, DocumentViewModel newValue)
- {
- WeakReferenceMessenger.Default.Send(new(oldValue, newValue));
- }
+ => WeakReferenceMessenger.Default.Send(new(oldValue, newValue));
public SettingsPanelViewModel SettingsViewModel { get; } = new SettingsPanelViewModel();
@@ -66,10 +64,7 @@ public async Task RestoreWorkspaceAsync(XamlDocument[] docs)
}
// If no active file was set, set it to the last one. (Rehydrate if on settings/welcome from old version).
- if (ActiveFile == null)
- {
- ActiveFile = OpenFiles.Last();
- }
+ ActiveFile ??= OpenFiles.Last();
}
private void OpenFiles_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
diff --git a/XamlStudio/ViewModels/SettingsPanelViewModel.cs b/XamlStudio/ViewModels/SettingsPanelViewModel.cs
index d60f707..bdadda4 100644
--- a/XamlStudio/ViewModels/SettingsPanelViewModel.cs
+++ b/XamlStudio/ViewModels/SettingsPanelViewModel.cs
@@ -46,7 +46,7 @@ partial void OnElementThemeChanged(ElementTheme value)
public SettingsService Settings { get; } = SettingsService.Instance;
- public ObservableCollection ThirdPartyLibs { get; set; } = new ObservableCollection();
+ public ObservableCollection ThirdPartyLibs { get; set; } = [];
public SettingsPanelViewModel()
{
@@ -97,13 +97,9 @@ private void SwitchToggle(RoutedEventArgs args)
}
[RelayCommand]
- private void DelayChanged(RangeBaseValueChangedEventArgs args)
- {
- Settings.AutoCompileDelay = args.NewValue;
-
- // TODO: Need to use a ThreadPoolTimer to wait for last change?
- ////Analytics.TrackEvent("Settings_CompileDelayChanged", new Dictionary {
- //// { "Value", "" + args.NewValue },
- ////});
- }
+ private void DelayChanged(RangeBaseValueChangedEventArgs args) => Settings.AutoCompileDelay = args.NewValue;
+ // TODO: Need to use a ThreadPoolTimer to wait for last change?
+ ////Analytics.TrackEvent("Settings_CompileDelayChanged", new Dictionary {
+ //// { "Value", "" + args.NewValue },
+ ////});
}
diff --git a/XamlStudio/ViewModels/ToolboxViewModel.cs b/XamlStudio/ViewModels/ToolboxViewModel.cs
index 8ab32bc..ea7c398 100644
--- a/XamlStudio/ViewModels/ToolboxViewModel.cs
+++ b/XamlStudio/ViewModels/ToolboxViewModel.cs
@@ -25,7 +25,7 @@ public partial class ToolboxViewModel : ObservableObject
IsSourceGrouped = true
};
- public ObservableCollection Favorites { get; } = new ObservableCollection();
+ public ObservableCollection Favorites { get; } = [];
[ObservableProperty]
public partial string Filter { get; set; } = string.Empty;
@@ -88,8 +88,7 @@ public async void Initialize()
}
partial void OnFilterChanged(string value)
- {
- LibraryView.Source = _groupedSource
+ => LibraryView.Source = _groupedSource
.SelectMany(group => group)
.Where(t => t.Name.Contains(value, StringComparison.OrdinalIgnoreCase) || t.Namespace.Contains(value, StringComparison.OrdinalIgnoreCase) || t.BaseType.Name.Contains(value, StringComparison.OrdinalIgnoreCase))
.ToGroup(api => api.Namespace)
@@ -98,5 +97,4 @@ partial void OnFilterChanged(string value)
.Where(t => t.Name.Contains(value, StringComparison.OrdinalIgnoreCase) || t.Namespace.Contains(value, StringComparison.OrdinalIgnoreCase) || t.BaseType.Name.Contains(value, StringComparison.OrdinalIgnoreCase))
.OrderBy(t => t.Name)
.ToGroup("Toolbox_Favorites_Header".GetLocalized()));
- }
}
diff --git a/XamlStudio/Views/Binding.xaml.cs b/XamlStudio/Views/Binding.xaml.cs
index 0049367..aac63c2 100644
--- a/XamlStudio/Views/Binding.xaml.cs
+++ b/XamlStudio/Views/Binding.xaml.cs
@@ -57,8 +57,5 @@ private void ListView_ItemClick(object sender, ItemClickEventArgs e)
}
}
- private void Button_ClearHistoryFilter_Click(object sender, RoutedEventArgs e)
- {
- HistoryFilter = null;
- }
+ private void Button_ClearHistoryFilter_Click(object sender, RoutedEventArgs e) => HistoryFilter = null;
}
diff --git a/XamlStudio/Views/DataSources.xaml.cs b/XamlStudio/Views/DataSources.xaml.cs
index 477f6bf..878ebc9 100644
--- a/XamlStudio/Views/DataSources.xaml.cs
+++ b/XamlStudio/Views/DataSources.xaml.cs
@@ -156,9 +156,11 @@ private void Clear_DataSource(object sender, RoutedEventArgs e)
private async void Open_DataSource(object sender, RoutedEventArgs e)
{
- var picker = new FileOpenPicker();
- picker.ViewMode = PickerViewMode.List;
- picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
+ var picker = new FileOpenPicker
+ {
+ ViewMode = PickerViewMode.List,
+ SuggestedStartLocation = PickerLocationId.DocumentsLibrary
+ };
picker.FileTypeFilter.Add(".json");
var file = await picker.PickSingleFileAsync();
@@ -174,11 +176,11 @@ private async void Open_DataSource(object sender, RoutedEventArgs e)
private async void Save_DataSource(object sender, RoutedEventArgs e)
{
- StorageFile file = null;
// Ensure if we can restore the file if it wasn't available on load
await _activeDocument.DataContext.RestoreFileAsync();
+ StorageFile file;
// Save As
if (!_activeDocument.DataContext.CanSave)
{
@@ -236,10 +238,12 @@ private static async Task SaveFile(DataContext document, StorageFile file)
private async Task SaveFileDialog(string documentName)
{
- var savePicker = new FileSavePicker();
- savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
+ var savePicker = new FileSavePicker
+ {
+ SuggestedStartLocation = PickerLocationId.DocumentsLibrary
+ };
// Dropdown of file types the user can save the file as
- savePicker.FileTypeChoices.Add("JavaScript Object Notation", new List() { ".json" });
+ savePicker.FileTypeChoices.Add("JavaScript Object Notation", [".json"]);
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = documentName;
diff --git a/XamlStudio/Views/Document.Design.xaml.cs b/XamlStudio/Views/Document.Design.xaml.cs
index 99df276..6e228af 100644
--- a/XamlStudio/Views/Document.Design.xaml.cs
+++ b/XamlStudio/Views/Document.Design.xaml.cs
@@ -249,15 +249,15 @@ public async void Receive(AddToXamlMessage message)
if (targetLine.Contains(message.Property))
{
var sp = targetLine.IndexOf(message.Property + "=") + message.Property.Length + 2;
- lines[loc.Line - 1] = targetLine.Substring(0, sp) + $"{message.Value}" + targetLine.Substring(targetLine.IndexOf("\"", sp + 1));
+ lines[loc.Line - 1] = targetLine[..sp] + $"{message.Value}" + targetLine[targetLine.IndexOf("\"", sp + 1)..];
}
else if (targetLine.Trim().EndsWith("/>"))
{
- lines[loc.Line - 1] = targetLine.Substring(0, targetLine.Length - 2) + $" {message.Property}=\"{message.Value}\"/>";
+ lines[loc.Line - 1] = targetLine[..^2] + $" {message.Property}=\"{message.Value}\"/>";
}
else if (targetLine.Trim().EndsWith(">"))
{
- lines[loc.Line - 1] = targetLine.Substring(0, targetLine.Length - 1) + $" {message.Property}=\"{message.Value}\">";
+ lines[loc.Line - 1] = targetLine[..^1] + $" {message.Property}=\"{message.Value}\">";
}
else
{
diff --git a/XamlStudio/Views/Document.xaml.cs b/XamlStudio/Views/Document.xaml.cs
index 156a096..24ceb1f 100644
--- a/XamlStudio/Views/Document.xaml.cs
+++ b/XamlStudio/Views/Document.xaml.cs
@@ -92,7 +92,7 @@ public bool IsSpecificPreviewSize
public static readonly DependencyProperty IsSpecificPreviewSizeProperty =
DependencyProperty.Register(nameof(IsSpecificPreviewSize), typeof(bool), typeof(Document), new PropertyMetadata(false));
- public ObservableCollection Breadcrumbs = new();
+ public ObservableCollection Breadcrumbs = [];
public Document()
{
@@ -115,17 +115,14 @@ private void Document_Loaded(object sender, RoutedEventArgs e)
// HACK: TODO: Workaround for Monaco editor not updating it's content?
ViewModel.Document.Content = ViewModel.Document.Content + " ";
- ViewModel.Document.Content = ViewModel.Document.Content.Substring(0, ViewModel.Document.Content.Length - 1);
+ ViewModel.Document.Content = ViewModel.Document.Content[..^1];
_ = UpdateBreadcrumbs();
SetPaneOrientation();
}
- private void Document_Unloaded(object sender, RoutedEventArgs e)
- {
- WeakReferenceMessenger.Default.UnregisterAll(this);
- }
+ private void Document_Unloaded(object sender, RoutedEventArgs e) => WeakReferenceMessenger.Default.UnregisterAll(this);
private void UnloadViewModel(DocumentViewModel model)
{
@@ -203,10 +200,7 @@ await languages.RegisterHoverProviderAsync("xml", (model, position) =>
});
}
- public async void Receive(NavigateToLineMessage message)
- {
- await CodeEditor.RevealLineInCenterIfOutsideViewportAsync(message.Line);
- }
+ public async void Receive(NavigateToLineMessage message) => await CodeEditor.RevealLineInCenterIfOutsideViewportAsync(message.Line);
public void Receive(InsertTextMessage message)
{
@@ -469,13 +463,11 @@ private void CodeEditor_KeyDown(Monaco.CodeEditor sender, Monaco.Helpers.WebKeyE
}
private void CodeEditor_OpenLinkRequested(WebView sender, WebViewNewWindowRequestedEventArgs args)
- {
- Analytics.TrackEvent("Open_Docs", new Dictionary {
- { "Location", "CodeEditor" },
- { "Type", _lastHoverType?.FullName ?? "Unknown" },
- { "Uri", args.Uri.ToString() },
- });
- }
+ => Analytics.TrackEvent("Open_Docs", new Dictionary {
+ { "Location", "CodeEditor" },
+ { "Type", _lastHoverType?.FullName ?? "Unknown" },
+ { "Uri", args.Uri.ToString() },
+ });
private void DocumentState_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
@@ -495,10 +487,7 @@ private void SetPaneOrientation()
var orientation = LoadedDocument.State.PreviewOrientation;
// If we're set to default, go grab that value to start from
- if (orientation == null)
- {
- orientation = SettingsService.Instance.DefaultPreviewPanePosition;
- }
+ orientation ??= SettingsService.Instance.DefaultPreviewPanePosition;
switch (orientation.Value)
{
@@ -529,12 +518,9 @@ private void SetPreviewAreaTheme()
}
#region Share Button Code
- private readonly Lazy _device = new Lazy(InitCanvas);
+ private readonly Lazy _device = new(InitCanvas);
- private static CanvasDevice InitCanvas()
- {
- return CanvasDevice.GetSharedDevice();
- }
+ private static CanvasDevice InitCanvas() => CanvasDevice.GetSharedDevice();
private CanvasBitmap _screenshotImage;
@@ -545,10 +531,7 @@ private async void ShareButton_Click(Microsoft.UI.Xaml.Controls.SplitButton send
DataTransferManager.ShowShareUI();
}
- private void ShareMenuEntireWindow_Click(object sender, RoutedEventArgs e)
- {
- ShareButton_Click(null, null);
- }
+ private void ShareMenuEntireWindow_Click(object sender, RoutedEventArgs e) => ShareButton_Click(null, null);
private async void ShareMenuPreviewOnly_Click(object sender, RoutedEventArgs e)
{
@@ -566,7 +549,7 @@ private async void DataTransferManager_DataRequested(DataTransferManager sender,
args.Request.Data.Properties.Title = "XAML Studio - " + LoadedDocument.Title;
- InMemoryRandomAccessStream inMemoryStream = new InMemoryRandomAccessStream();
+ InMemoryRandomAccessStream inMemoryStream = new();
await _screenshotImage.SaveAsync(inMemoryStream, CanvasBitmapFileFormat.Png); // TODO: Have Option for quality?
@@ -612,10 +595,7 @@ private async void BreadcrumbBar_ItemClicked(Microsoft.UI.Xaml.Controls.Breadcru
}
}
- private void CodeEditor_SelectedRangeChanged(DependencyObject sender, DependencyProperty dp)
- {
- _ = UpdateBreadcrumbs();
- }
+ private void CodeEditor_SelectedRangeChanged(DependencyObject sender, DependencyProperty dp) => _ = UpdateBreadcrumbs();
private async Task UpdateBreadcrumbs()
{
diff --git a/XamlStudio/Views/DocumentToViewModelConverter.cs b/XamlStudio/Views/DocumentToViewModelConverter.cs
index 73fb6b8..faaec81 100644
--- a/XamlStudio/Views/DocumentToViewModelConverter.cs
+++ b/XamlStudio/Views/DocumentToViewModelConverter.cs
@@ -30,8 +30,5 @@ public object Convert(object value, Type targetType, object parameter, string la
return DependencyProperty.UnsetValue;
}
- public object ConvertBack(object value, Type targetType, object parameter, string language)
- {
- throw new NotImplementedException();
- }
+ public object ConvertBack(object value, Type targetType, object parameter, string language) => throw new NotImplementedException();
}
diff --git a/XamlStudio/Views/Explorer.xaml.cs b/XamlStudio/Views/Explorer.xaml.cs
index c07206e..2a910ad 100644
--- a/XamlStudio/Views/Explorer.xaml.cs
+++ b/XamlStudio/Views/Explorer.xaml.cs
@@ -60,10 +60,12 @@ private void WorkspaceFolders_CollectionChanged(object sender, System.Collection
private void InitializeTreeView(FolderLocation folder)
{
// FYI A TreeView can have more than 1 root node. TODO: Support multiple workspaces? Or would we just separate outside the TreeView anyway?
- muxc.TreeViewNode mainNode = new muxc.TreeViewNode();
- mainNode.Content = folder.BackingFolder;
- mainNode.IsExpanded = true;
- mainNode.HasUnrealizedChildren = true;
+ muxc.TreeViewNode mainNode = new()
+ {
+ Content = folder.BackingFolder,
+ IsExpanded = true,
+ HasUnrealizedChildren = true
+ };
FillTreeNode(mainNode);
WorkspaceTreeView.RootNodes.Add(mainNode);
@@ -76,8 +78,7 @@ private async void FillTreeNode(muxc.TreeViewNode node)
// Add each item as a new child node of the node that's being expanded.
// Only process the node if it's a folder and has unrealized children.
- StorageFolder folder = null;
-
+ StorageFolder folder;
if (node.Content is StorageFolder && node.HasUnrealizedChildren == true)
{
folder = node.Content as StorageFolder;
@@ -99,8 +100,10 @@ private async void FillTreeNode(muxc.TreeViewNode node)
foreach (var item in itemsList)
{
- var newNode = new muxc.TreeViewNode();
- newNode.Content = item;
+ var newNode = new muxc.TreeViewNode
+ {
+ Content = item
+ };
if (item is StorageFolder)
{
@@ -160,12 +163,12 @@ private void WorkspaceTreeView_ItemInvoked(muxc.TreeView sender, muxc.TreeViewIt
case StorageFile file when ExplorerItemTemplateSelector.DataFileTypes.Contains(file.FileType.ToLower()):
// Insert the d:DataContext="{d:DesignData /SampleData/XAMLing.json}" attribute
// TODO: Should we instead explicitly update/insert this into root tag?
- WeakReferenceMessenger.Default.Send(new($"d:DataContext=\"{{d:DesignData {file.Path.Replace('\\', '/').Substring(workspacePathLength)}}}\""));
+ WeakReferenceMessenger.Default.Send(new($"d:DataContext=\"{{d:DesignData {file.Path.Replace('\\', '/')[workspacePathLength..]}}}\""));
Analytics.TrackEvent("Explorer_Workspace_InsertDataContext");
break;
case StorageFile file when ExplorerItemTemplateSelector.ImageFileTypes.Contains(file.FileType.ToLower()):
// Insert image tag into document
- WeakReferenceMessenger.Default.Send(new($""));
+ WeakReferenceMessenger.Default.Send(new($""));
Analytics.TrackEvent("Explorer_Workspace_InsertImage");
break;
case StorageFile file when ExplorerItemTemplateSelector.XamlFileTypes.Contains(file.FileType.ToLower()):
diff --git a/XamlStudio/Views/MainPage.xaml.cs b/XamlStudio/Views/MainPage.xaml.cs
index 3d6c79d..638ce6f 100644
--- a/XamlStudio/Views/MainPage.xaml.cs
+++ b/XamlStudio/Views/MainPage.xaml.cs
@@ -80,11 +80,9 @@ public MainPage()
}
private void CoreTitleBar_LayoutMetricsChanged(CoreApplicationViewTitleBar sender, object args)
- {
- // Get the size of the caption controls and set padding.
- ////LeftPaddingColumn.Width = new GridLength(coreTitleBar.SystemOverlayLeftInset);
- RightPaddingColumn.Width = new GridLength(sender.SystemOverlayRightInset);
- }
+ // Get the size of the caption controls and set padding.
+ ////LeftPaddingColumn.Width = new GridLength(coreTitleBar.SystemOverlayLeftInset);
+ => RightPaddingColumn.Width = new GridLength(sender.SystemOverlayRightInset);
private void Instance_OnBackgroundEntering(object sender, OnBackgroundEnteringEventArgs e)
{
@@ -228,7 +226,7 @@ public void Receive(KeyDownMessage keyInfo)
private async void MainPage_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
// Offload from main thread to parallelize assembly loading.
- Task t = new Task(async () =>
+ Task t = new(async () =>
{
// TODO: Clean-up these initialize calls to make sure this list is centralized...
await AppAssemblyInfo.Instance.InitializeAsync(new Assembly[] {
@@ -396,9 +394,7 @@ public void OpenFileItems(IStorageItem[] files)
}
private void DocumentTabs_TabClosing(Microsoft.UI.Xaml.Controls.TabView sender, Microsoft.UI.Xaml.Controls.TabViewTabCloseRequestedEventArgs args)
- {
- ViewModel.CloseActiveDocumentCommand.Execute(args.Item);
- }
+ => ViewModel.CloseActiveDocumentCommand.Execute(args.Item);
private void NavMenu_ItemInvoked(MUXC.NavigationView sender, MUXC.NavigationViewItemInvokedEventArgs args)
{
diff --git a/XamlStudio/Views/Properties.xaml.cs b/XamlStudio/Views/Properties.xaml.cs
index af8d413..29b391b 100644
--- a/XamlStudio/Views/Properties.xaml.cs
+++ b/XamlStudio/Views/Properties.xaml.cs
@@ -124,10 +124,7 @@ private void ListView_ItemClick(object sender, ItemClickEventArgs e)
}
}
- public void Receive(SelectedVisualElementMessage message)
- {
- UpdateProperties(message.Element);
- }
+ public void Receive(SelectedVisualElementMessage message) => UpdateProperties(message.Element);
public void Receive(EditorSelectedElementMessage message)
{
@@ -156,7 +153,7 @@ private void UpdateProperties(DependencyObject element, IXmlElementSyntax xmlHin
if (VisualTreeHelper.GetChildrenCount(element) is int count && count > 0)
{
- List children = new();
+ List children = [];
for (int i = 0; i < count; i++)
{
children.Add(VisualTreeHelper.GetChild(element, i));
@@ -169,8 +166,8 @@ private void UpdateProperties(DependencyObject element, IXmlElementSyntax xmlHin
}
// Find properties of interest...
- List properties = new();
- List unsetProperties = new();
+ List properties = [];
+ List unsetProperties = [];
// Helper Function to Add Property Values to our List (if value is set)
PropertyInfo AddProperty(Type type, string propName, string? group = null)
@@ -202,7 +199,7 @@ PropertyInfo AddProperty(Type type, string propName, string? group = null)
// TODO: Pinned...
- HashSet definedAttributes = new();
+ HashSet definedAttributes = [];
// Check if we have an associated XML element to see what we set in our Editor text
if (xmlHint == null
@@ -216,7 +213,7 @@ PropertyInfo AddProperty(Type type, string propName, string? group = null)
}
}
- List groupOrder = new() { "- Modified -", "- Set in XAML -" };
+ List groupOrder = ["- Modified -", "- Set in XAML -"];
PropertyInfo unset = null;
@@ -255,7 +252,7 @@ PropertyInfo AddProperty(Type type, string propName, string? group = null)
.OrderBy(g => groupOrder.IndexOf(g.Key)));
// Check for Visual States
- ViewModel.VisualStates = new();
+ ViewModel.VisualStates = [];
if (element is FrameworkElement fe)
{
_visualStateWatcher = new(fe);
diff --git a/XamlStudio/Views/SettingsPanelPage.xaml.cs b/XamlStudio/Views/SettingsPanelPage.xaml.cs
index de452f8..5c04637 100644
--- a/XamlStudio/Views/SettingsPanelPage.xaml.cs
+++ b/XamlStudio/Views/SettingsPanelPage.xaml.cs
@@ -180,10 +180,7 @@ private void NamespaceDataGrid_PreparingCellForEdit(object sender, Microsoft.Too
}
}
- private async Task AreAnalyticsOn()
- {
- return await Analytics.IsEnabledAsync();
- }
+ private async Task AreAnalyticsOn() => await Analytics.IsEnabledAsync();
public Visibility FeedbackVisibility => StoreServicesFeedbackLauncher.IsSupported() ? Visibility.Visible : Visibility.Collapsed;
diff --git a/XamlStudio/Views/StorageFileThumbnailConverter.cs b/XamlStudio/Views/StorageFileThumbnailConverter.cs
index c1f9022..3212864 100644
--- a/XamlStudio/Views/StorageFileThumbnailConverter.cs
+++ b/XamlStudio/Views/StorageFileThumbnailConverter.cs
@@ -27,20 +27,17 @@ public object Convert(object value, Type targetType, object parameter, string la
if (value is StorageFile file)
{
var result = new BitmapImage();
- Task t = new Task(async () =>
+ Task t = new(async () =>
{
if (file.IsAvailable)
{
var thumbnail = await file.GetScaledImageAsThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView, 128, Windows.Storage.FileProperties.ThumbnailOptions.ResizeThumbnail);
- if (thumbnail == null)
- {
- thumbnail = await file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView, 128, Windows.Storage.FileProperties.ThumbnailOptions.ResizeThumbnail);
- }
+ thumbnail ??= await file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView, 128, Windows.Storage.FileProperties.ThumbnailOptions.ResizeThumbnail);
if (thumbnail != null)
{
- InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
+ InMemoryRandomAccessStream randomAccessStream = new();
await RandomAccessStream.CopyAsync(thumbnail, randomAccessStream);
randomAccessStream.Seek(0);
await _queue.EnqueueAsync(async () =>
@@ -67,8 +64,5 @@ await _queue.EnqueueAsync(async () =>
return DependencyProperty.UnsetValue;
}
- public object ConvertBack(object value, Type targetType, object parameter, string language)
- {
- throw new NotImplementedException();
- }
+ public object ConvertBack(object value, Type targetType, object parameter, string language) => throw new NotImplementedException();
}
diff --git a/XamlStudio/Views/WelcomePage.xaml.cs b/XamlStudio/Views/WelcomePage.xaml.cs
index 54f837e..9848c46 100644
--- a/XamlStudio/Views/WelcomePage.xaml.cs
+++ b/XamlStudio/Views/WelcomePage.xaml.cs
@@ -26,7 +26,7 @@ public MainViewModel MainViewModel
public static readonly DependencyProperty MainViewModelProperty =
DependencyProperty.Register("MainViewModel", typeof(MainViewModel), typeof(WelcomePage), new PropertyMetadata(null));
- public ObservableCollection RecentFiles { get; set; } = new ObservableCollection();
+ public ObservableCollection RecentFiles { get; set; } = [];
public WelcomePage()
{