diff --git a/WinUIGallery/App.xaml.cs b/WinUIGallery/App.xaml.cs index e2e2afe8c..84d4897e9 100644 --- a/WinUIGallery/App.xaml.cs +++ b/WinUIGallery/App.xaml.cs @@ -109,10 +109,11 @@ private async void EnsureWindow() var targetPageArguments = string.Empty; AppActivationArguments eventArgs = AppInstance.GetCurrent().GetActivatedEventArgs(); - if (eventArgs != null && eventArgs.Kind == ExtendedActivationKind.Protocol && eventArgs.Data is ProtocolActivatedEventArgs) + if (eventArgs != null && + eventArgs.Kind == ExtendedActivationKind.Protocol && + eventArgs.Data is ProtocolActivatedEventArgs protocolArgs) { - var ProtocolArgs = eventArgs.Data as ProtocolActivatedEventArgs; - string uri = ProtocolArgs.Uri.LocalPath.Replace("/", ""); + string uri = protocolArgs.Uri.LocalPath.Replace("/", ""); targetPageArguments = uri; if (uri == "AllControls") @@ -155,7 +156,7 @@ private void HandleExceptions(object sender, Microsoft.UI.Xaml.UnhandledExceptio if (NativeMethods.IsAppPackaged) { e.Handled = true; //Don't crash the app. - + //Create the notification. var notification = new AppNotificationBuilder() .AddText("An exception was thrown.") @@ -163,7 +164,7 @@ private void HandleExceptions(object sender, Microsoft.UI.Xaml.UnhandledExceptio .AddText($"Message: {e.Message}\r\n" + $"HResult: {e.Exception.HResult}") .BuildNotification(); - + //Show the notification AppNotificationManager.Default.Show(notification); } diff --git a/WinUIGallery/Controls/ControlExample.xaml.cs b/WinUIGallery/Controls/ControlExample.xaml.cs index 393214eb6..466a7ac87 100644 --- a/WinUIGallery/Controls/ControlExample.xaml.cs +++ b/WinUIGallery/Controls/ControlExample.xaml.cs @@ -19,12 +19,12 @@ namespace WinUIGallery.Controls; /// public sealed class ControlExampleSubstitution : DependencyObject { - public event TypedEventHandler ValueChanged; + public event TypedEventHandler? ValueChanged; - public string Key { get; set; } + public string Key { get; set; } = string.Empty; - private object _value = null; - public object Value + private object? _value = null; + public object? Value { get { return _value; } set @@ -52,7 +52,7 @@ public string ValueAsString() return string.Empty; } - object value = Value; + object? value = Value; // For solid color brushes, use the underlying color. if (value is SolidColorBrush) @@ -60,12 +60,7 @@ public string ValueAsString() value = ((SolidColorBrush)value).Color; } - if (value == null) - { - return string.Empty; - } - - return value.ToString(); + return value?.ToString() ?? string.Empty; } } @@ -193,15 +188,19 @@ private enum SyntaxHighlightLanguage { Xml, CSharp }; private void SelectorBarItem_Loaded(object sender, RoutedEventArgs e) { - var item = sender as SelectorBarItem; - if (item == null) + if (sender is not SelectorBarItem item) return; - if (item.Tag.ToString().Equals("Xaml", StringComparison.OrdinalIgnoreCase)) + PrepareSelectorBarItem(item); + } + + private void PrepareSelectorBarItem(SelectorBarItem item) + { + if (item.Tag.ToString()?.Equals("Xaml", StringComparison.OrdinalIgnoreCase) is true) { item.Visibility = string.IsNullOrEmpty(Xaml) && string.IsNullOrEmpty(XamlSource) ? Visibility.Collapsed : Visibility.Visible; } - else if (item.Tag.ToString().Equals("CSharp", StringComparison.OrdinalIgnoreCase)) + else if (item.Tag.ToString()?.Equals("CSharp", StringComparison.OrdinalIgnoreCase) is true) { item.Visibility = string.IsNullOrEmpty(CSharp) && string.IsNullOrEmpty(CSharpSource) ? Visibility.Collapsed : Visibility.Visible; } @@ -217,19 +216,18 @@ private void SelectorBarItem_Loaded(object sender, RoutedEventArgs e) private static void OnXamlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { - var ctrl = (ControlExample)d; - if (ctrl != null) - { - ctrl.SelectorBarItem_Loaded(ctrl.SelectorBarXamlItem, null); - } + if (d is not ControlExample ctrl) + return; + + ctrl.PrepareSelectorBarItem(ctrl.SelectorBarXamlItem); } + private static void OnCSharpChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { - var ctrl = (ControlExample)d; - if (ctrl != null) - { - ctrl.SelectorBarItem_Loaded(ctrl.SelectorBarCSharpItem, null); - } + if (d is not ControlExample ctrl) + return; + + ctrl.PrepareSelectorBarItem(ctrl.SelectorBarCSharpItem); } private void SelectorBarControl_SelectionChanged(SelectorBar sender, SelectorBarSelectionChangedEventArgs args) @@ -242,12 +240,12 @@ private void HandlePresenterVisibility() var selectedItem = SelectorBarControl.SelectedItem; if (selectedItem != null) { - if (selectedItem.Tag.ToString().Equals("Xaml", StringComparison.OrdinalIgnoreCase)) + if (selectedItem.Tag.ToString()?.Equals("Xaml", StringComparison.OrdinalIgnoreCase) is true) { XamlContentPresenter.Visibility = Visibility.Visible; CSharpContentPresenter.Visibility = Visibility.Collapsed; } - else if (selectedItem.Tag.ToString().Equals("CSharp", StringComparison.OrdinalIgnoreCase)) + else if (selectedItem.Tag.ToString()?.Equals("CSharp", StringComparison.OrdinalIgnoreCase) is true) { CSharpContentPresenter.Visibility = Visibility.Visible; XamlContentPresenter.Visibility = Visibility.Collapsed; diff --git a/WinUIGallery/Controls/DesignGuidance/ColorTile.xaml.cs b/WinUIGallery/Controls/DesignGuidance/ColorTile.xaml.cs index 1c361e486..3e79a4f59 100644 --- a/WinUIGallery/Controls/DesignGuidance/ColorTile.xaml.cs +++ b/WinUIGallery/Controls/DesignGuidance/ColorTile.xaml.cs @@ -75,6 +75,9 @@ private void CopyBrushNameButton_Click(object sender, RoutedEventArgs e) package.SetText(ColorBrushName); Clipboard.SetContent(package); - UIHelper.AnnounceActionForAccessibility(sender as Button, "Brush name copied to clipboard", "BrushNameCopiedSuccessNotificationId"); + if (sender is Button button) + { + UIHelper.AnnounceActionForAccessibility(button, "Brush name copied to clipboard", "BrushNameCopiedSuccessNotificationId"); + } } } diff --git a/WinUIGallery/Controls/InlineColorPicker.xaml.cs b/WinUIGallery/Controls/InlineColorPicker.xaml.cs index 7515fdb29..74edeb25a 100644 --- a/WinUIGallery/Controls/InlineColorPicker.xaml.cs +++ b/WinUIGallery/Controls/InlineColorPicker.xaml.cs @@ -40,7 +40,7 @@ public SolidColorBrush ColorBrush public static readonly DependencyProperty ColorBrushProperty = DependencyProperty.Register("ColorBrush", typeof(SolidColorBrush), typeof(InlineColorPicker), new PropertyMetadata(new SolidColorBrush(Microsoft.UI.Colors.White))); - public event EventHandler ColorChanged; + public event EventHandler? ColorChanged; public InlineColorPicker() { diff --git a/WinUIGallery/Controls/PageHeader.xaml.cs b/WinUIGallery/Controls/PageHeader.xaml.cs index dd3b6f4bf..43da6ea29 100644 --- a/WinUIGallery/Controls/PageHeader.xaml.cs +++ b/WinUIGallery/Controls/PageHeader.xaml.cs @@ -21,17 +21,17 @@ public Visibility ThemeButtonVisibility public static readonly DependencyProperty ThemeButtonVisibilityProperty = DependencyProperty.Register("ThemeButtonVisibility", typeof(Visibility), typeof(PageHeader), new PropertyMetadata(Visibility.Visible)); - public string PageName { get; set; } - public Action CopyLinkAction { get; set; } - public Action ToggleThemeAction { get; set; } + public string PageName { get; set; } = string.Empty; + public Action? CopyLinkAction { get; set; } + public Action? ToggleThemeAction { get; set; } - public ControlInfoDataItem Item + public ControlInfoDataItem? Item { get { return _item; } set { _item = value; } } - private ControlInfoDataItem _item; + private ControlInfoDataItem? _item; public PageHeader() { @@ -86,6 +86,11 @@ private void OnCopyDontShowAgainButtonClick(TeachingTip sender, object args) private void OnCopyLink() { + if (this.Item is null) + { + return; + } + ProtocolActivationClipboardHelper.Copy(this.Item); } public async void OnFeedBackButtonClick(object sender, RoutedEventArgs e) @@ -107,12 +112,12 @@ private void UserControl_Loaded(object sender, RoutedEventArgs e) private string GetFavoriteGlyph(bool? isFavorite) { - return (bool)isFavorite ? "\uE735" : "\uE734"; + return isFavorite is true ? "\uE735" : "\uE734"; } private string GetFavoriteToolTip(bool? isFavorite) { - return (bool)isFavorite ? "Remove from favorites" : "Add to favorites"; + return isFavorite is true ? "Remove from favorites" : "Add to favorites"; } private void FavoriteButton_Click(object sender, RoutedEventArgs e) diff --git a/WinUIGallery/Controls/SampleCodePresenter.xaml.cs b/WinUIGallery/Controls/SampleCodePresenter.xaml.cs index e9e4ee5d2..d6a82f60d 100644 --- a/WinUIGallery/Controls/SampleCodePresenter.xaml.cs +++ b/WinUIGallery/Controls/SampleCodePresenter.xaml.cs @@ -60,7 +60,7 @@ public IList Substitutions private string actualCode = ""; private static Regex SubstitutionPattern = new Regex(@"\$\(([^\)]+)\)"); - private RichTextBlock sampleCodeRTB; + private RichTextBlock? sampleCodeRTB; public SampleCodePresenter() { @@ -126,7 +126,7 @@ private void SampleCodePresenter_ActualThemeChanged(FrameworkElement sender, obj GenerateSyntaxHighlightedContent(); } - private void OnValueChanged(ControlExampleSubstitution sender, object e) + private void OnValueChanged(ControlExampleSubstitution sender, object? _) { GenerateSyntaxHighlightedContent(); } @@ -166,8 +166,7 @@ private async void FormatAndRenderSampleFromFile(string sourceRelativePath, Cont { if (sourceRelativePath != null && sourceRelativePath.EndsWith("txt")) { - string sampleString = null; - StorageFile file = null; + StorageFile? file = null; if (!NativeMethods.IsAppPackaged) { var relativePath = GetDerivedSourceUnpackaged(sourceRelativePath); @@ -182,7 +181,7 @@ private async void FormatAndRenderSampleFromFile(string sourceRelativePath, Cont file = await StorageFile.GetFileFromApplicationUriAsync(derivedSource); } - sampleString = await FileIO.ReadTextAsync(file); + string sampleString = await FileIO.ReadTextAsync(file); FormatAndRenderSampleFromString(sampleString, presenter, highlightLanguage); } @@ -319,7 +318,7 @@ private void CopyCodeButton_Click(object sender, RoutedEventArgs e) private void CodeScrollViewer_Loaded(object sender, RoutedEventArgs e) { - ScrollBar horizontalScrollBar = FindHorizontalScrollBar(CodeScrollViewer); + ScrollBar? horizontalScrollBar = FindHorizontalScrollBar(CodeScrollViewer); if (horizontalScrollBar != null) { // Create a timer and store it in the ScrollBar's Tag property. @@ -361,7 +360,7 @@ private void HorizontalScrollBar_Scroll(object sender, ScrollEventArgs e) } } - private ScrollBar FindHorizontalScrollBar(DependencyObject element) + private ScrollBar? FindHorizontalScrollBar(DependencyObject element) { if (element is ScrollBar sb && sb.Orientation == Orientation.Horizontal) { diff --git a/WinUIGallery/Converters/MenuItemTemplateSelector.cs b/WinUIGallery/Converters/MenuItemTemplateSelector.cs index d5133003e..75f66a13a 100644 --- a/WinUIGallery/Converters/MenuItemTemplateSelector.cs +++ b/WinUIGallery/Converters/MenuItemTemplateSelector.cs @@ -12,14 +12,14 @@ namespace WinUIGallery.Converters; [ContentProperty(Name = "ItemTemplate")] partial class MenuItemTemplateSelector : DataTemplateSelector { - public DataTemplate ItemTemplate { get; set; } + public DataTemplate? ItemTemplate { get; set; } - protected override DataTemplate SelectTemplateCore(object item) + protected override DataTemplate? SelectTemplateCore(object item) { return item is Separator ? SeparatorTemplate : item is Header ? HeaderTemplate : ItemTemplate; } - protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) + protected override DataTemplate? SelectTemplateCore(object item, DependencyObject container) { return item is Separator ? SeparatorTemplate : item is Header ? HeaderTemplate : ItemTemplate; } diff --git a/WinUIGallery/Helpers/ControlInfoDataSource.cs b/WinUIGallery/Helpers/ControlInfoDataSource.cs index d49a5077a..7b4da0555 100644 --- a/WinUIGallery/Helpers/ControlInfoDataSource.cs +++ b/WinUIGallery/Helpers/ControlInfoDataSource.cs @@ -54,7 +54,7 @@ public async Task> GetGroupsAsync() return _instance.Groups; } - public static async Task GetGroupAsync(string uniqueId) + public static async Task GetGroupAsync(string uniqueId) { await _instance.GetControlInfoDataAsync(); // Simple linear search is acceptable for small data sets @@ -63,7 +63,7 @@ public static async Task GetGroupAsync(string uniqueId) return null; } - public static async Task GetItemAsync(string uniqueId) + public static async Task GetItemAsync(string uniqueId) { await _instance.GetControlInfoDataAsync(); // Simple linear search is acceptable for small data sets @@ -72,7 +72,7 @@ public static async Task GetItemAsync(string uniqueId) return null; } - public static async Task GetGroupFromItemAsync(string uniqueId) + public static async Task GetGroupFromItemAsync(string uniqueId) { await _instance.GetControlInfoDataAsync(); var matches = _instance.Groups.Where((group) => group.Items.FirstOrDefault(item => item.UniqueId.Equals(uniqueId)) != null); @@ -93,19 +93,23 @@ private async Task GetControlInfoDataAsync() var jsonText = await FileLoader.LoadText("Samples/Data/ControlInfoData.json"); var controlInfoDataGroup = JsonSerializer.Deserialize(jsonText, typeof(Root), RootContext.Default) as Root; + if (controlInfoDataGroup is null) + { + return; + } + lock (_lock) { string pageRoot = "WinUIGallery.ControlPages."; controlInfoDataGroup.Groups.SelectMany(g => g.Items).ToList().ForEach(item => { -#nullable enable - string? badgeString = item switch + string badgeString = item switch { { IsNew: true } => "New", { IsUpdated: true } => "Updated", { IsPreview: true } => "Preview", - _ => null + _ => string.Empty, }; string pageString = $"{pageRoot}{item.UniqueId}Page"; Type? pageType = Type.GetType(pageString); @@ -113,7 +117,6 @@ private async Task GetControlInfoDataAsync() item.BadgeString = badgeString; item.IncludedInBuild = pageType is not null; item.ImagePath ??= "ms-appx:///Assets/ControlImages/Placeholder.png"; -#nullable disable }); foreach (var group in controlInfoDataGroup.Groups) diff --git a/WinUIGallery/Helpers/FileLoader.cs b/WinUIGallery/Helpers/FileLoader.cs index 0ececf887..f3f16a8b9 100644 --- a/WinUIGallery/Helpers/FileLoader.cs +++ b/WinUIGallery/Helpers/FileLoader.cs @@ -14,7 +14,7 @@ internal partial class FileLoader { public static async Task LoadText(string relativeFilePath) { - StorageFile file = null; + StorageFile? file = null; if (!NativeMethods.IsAppPackaged) { var sourcePath = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, relativeFilePath)); diff --git a/WinUIGallery/Helpers/IconsDataSource.cs b/WinUIGallery/Helpers/IconsDataSource.cs index 4a4191746..1fd77fe96 100644 --- a/WinUIGallery/Helpers/IconsDataSource.cs +++ b/WinUIGallery/Helpers/IconsDataSource.cs @@ -31,10 +31,12 @@ public async Task> LoadIcons() var jsonText = await FileLoader.LoadText("Samples/Data/IconsData.json"); lock (_lock) { - if (icons.Count == 0) + if (icons.Count == 0 && + JsonSerializer.Deserialize(jsonText, typeof(List), IconDataListContext.Default) is List loadedIcons) { - icons = JsonSerializer.Deserialize(jsonText, typeof(List), IconDataListContext.Default) as List; + icons = loadedIcons; } + return icons; } } diff --git a/WinUIGallery/Helpers/IdleSynchronizer.cs b/WinUIGallery/Helpers/IdleSynchronizer.cs index 33b2e675a..b25b56cb7 100644 --- a/WinUIGallery/Helpers/IdleSynchronizer.cs +++ b/WinUIGallery/Helpers/IdleSynchronizer.cs @@ -23,7 +23,7 @@ public partial class IdleSynchronizer const string s_imageDecodingIdleHandleName = "ImageDecodingIdle"; const string s_fontDownloadsIdleHandleName = "FontDownloadsIdle"; - private DispatcherQueue m_dispatcherQueue = null; + private DispatcherQueue m_dispatcherQueue; private SafeHandle m_hasAnimationsHandle; private SafeHandle m_animationsCompleteHandle; @@ -86,7 +86,7 @@ private uint GetUIThreadId(DispatcherQueue dispatcherQueue) return threadId; } - private static IdleSynchronizer instance = null; + private static IdleSynchronizer? instance = null; public static IdleSynchronizer Instance { @@ -101,7 +101,7 @@ public static IdleSynchronizer Instance } } - public string Log { get; set; } + public string? Log { get; set; } public int TickCountBegin { get; set; } private IdleSynchronizer(DispatcherQueue dispatcherQueue) @@ -283,7 +283,7 @@ void WaitForIdleDispatcher() timer.Interval = TimeSpan.FromMilliseconds(0); timer.IsRepeating = false; - TypedEventHandler tickHandler = null; + TypedEventHandler? tickHandler = null; tickHandler = (sender, args) => { @@ -315,7 +315,7 @@ string WaitForAnimationsComplete(out bool hadAnimations) { return "HasAnimations handle wait returned an invalid value."; } - + AddLog("WaitForAnimationsComplete: After Wait(m_hasAnimationsHandle)"); bool hasAnimations = (waitResult == WAIT_EVENT.WAIT_OBJECT_0); diff --git a/WinUIGallery/Helpers/NativeMethods.cs b/WinUIGallery/Helpers/NativeMethods.cs index 4f8aedb18..4716e83e5 100644 --- a/WinUIGallery/Helpers/NativeMethods.cs +++ b/WinUIGallery/Helpers/NativeMethods.cs @@ -24,7 +24,7 @@ internal partial class NativeMethods [DllImport("user32.dll")] internal static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, WindowMessage Msg, IntPtr wParam, IntPtr lParam); - + internal unsafe static void SetWindowKeyHook() { delegate* unmanaged[Stdcall] callback = &HookCallback; @@ -66,7 +66,7 @@ internal enum WindowMessage : int } internal static bool IsAppPackaged { get; } = GetCurrentPackageName() != null; - internal static string GetCurrentPackageName() + internal static string? GetCurrentPackageName() { unsafe { diff --git a/WinUIGallery/Helpers/NavigationHelper.cs b/WinUIGallery/Helpers/NavigationHelper.cs index 39f6cf748..cee9f30ae 100644 --- a/WinUIGallery/Helpers/NavigationHelper.cs +++ b/WinUIGallery/Helpers/NavigationHelper.cs @@ -72,21 +72,21 @@ public NavigationHelper(Page page) #region Process lifetime management - private string _pageKey; + private string _pageKey = string.Empty; /// /// Handle this event to populate the page using content passed /// during navigation as well as any state that was saved by /// the SaveState event handler. /// - public event LoadStateEventHandler LoadState; + public event LoadStateEventHandler? LoadState; /// /// Handle this event to save state that can be used by /// the LoadState event handler. Save the state in case /// the application is suspended or the page is discarded /// from the navigation cache. /// - public event SaveStateEventHandler SaveState; + public event SaveStateEventHandler? SaveState; /// /// Invoked when this page is about to be displayed in a Frame. @@ -162,8 +162,8 @@ public void OnNavigatedFrom(NavigationEventArgs e) [Windows.Foundation.Metadata.WebHostHidden] public partial class RootFrameNavigationHelper { - private Frame Frame { get; set; } - private NavigationView CurrentNavView { get; set; } + private Frame? Frame { get; set; } + private NavigationView? CurrentNavView { get; set; } #nullable enable private static RootFrameNavigationHelper? instance; @@ -261,12 +261,13 @@ private bool TryGoBack() { bool navigated = false; // Don't go back if the nav pane is overlayed. - if (this.CurrentNavView.IsPaneOpen && (this.CurrentNavView.DisplayMode == NavigationViewDisplayMode.Compact || this.CurrentNavView.DisplayMode == NavigationViewDisplayMode.Minimal)) + if (this.CurrentNavView?.IsPaneOpen is true && + (this.CurrentNavView.DisplayMode == NavigationViewDisplayMode.Compact || this.CurrentNavView.DisplayMode == NavigationViewDisplayMode.Minimal)) { return navigated; } - if (this.Frame.CanGoBack) + if (this.Frame?.CanGoBack is true) { this.Frame.GoBack(); navigated = true; @@ -278,7 +279,7 @@ private bool TryGoBack() private bool TryGoForward() { bool navigated = false; - if (this.Frame.CanGoForward) + if (this.Frame?.CanGoForward is true) { this.Frame.GoForward(); navigated = true; @@ -310,7 +311,7 @@ public partial class LoadStateEventArgs : EventArgs /// A dictionary of state preserved by this page during an earlier /// session. This will be null the first time a page is visited. /// - public Dictionary PageState { get; private set; } + public Dictionary? PageState { get; private set; } /// /// Initializes a new instance of the class. @@ -323,7 +324,7 @@ public partial class LoadStateEventArgs : EventArgs /// A dictionary of state preserved by this page during an earlier /// session. This will be null the first time a page is visited. /// - public LoadStateEventArgs(object navigationParameter, Dictionary pageState) + public LoadStateEventArgs(object navigationParameter, Dictionary? pageState) : base() { this.NavigationParameter = navigationParameter; diff --git a/WinUIGallery/Helpers/ProcessInfoHelper.cs b/WinUIGallery/Helpers/ProcessInfoHelper.cs index 8a9b89c51..b188462b9 100644 --- a/WinUIGallery/Helpers/ProcessInfoHelper.cs +++ b/WinUIGallery/Helpers/ProcessInfoHelper.cs @@ -4,18 +4,18 @@ namespace WinUIGallery.Helpers; public static partial class ProcessInfoHelper { - private static readonly FileVersionInfo _fileVersionInfo; + private static readonly FileVersionInfo? _fileVersionInfo; private static readonly Process _process; static ProcessInfoHelper() { _process = Process.GetCurrentProcess(); - _fileVersionInfo = _process.MainModule.FileVersionInfo; + _fileVersionInfo = _process.MainModule?.FileVersionInfo; } /// /// Returns the version string. /// - public static string Version => GetVersion()?.ToString(); + public static string Version => GetVersion()?.ToString() ?? string.Empty; /// /// Returns the version string prefixed with 'v'. @@ -37,16 +37,18 @@ static ProcessInfoHelper() /// public static string Publisher => _fileVersionInfo?.CompanyName ?? "Unknown Publisher"; - public static Version GetVersion() + public static Version? GetVersion() { - return new Version(_fileVersionInfo.FileMajorPart, _fileVersionInfo.FileMinorPart, _fileVersionInfo.FileBuildPart, _fileVersionInfo.FilePrivatePart); + return _fileVersionInfo is null + ? null + : new Version(_fileVersionInfo.FileMajorPart, _fileVersionInfo.FileMinorPart, _fileVersionInfo.FileBuildPart, _fileVersionInfo.FilePrivatePart); } /// /// Retrieves the file version information for the current assembly. /// /// Returns a FileVersionInfo object containing version details. - public static FileVersionInfo GetFileVersionInfo() + public static FileVersionInfo? GetFileVersionInfo() { return _fileVersionInfo; } diff --git a/WinUIGallery/Helpers/SettingsHelper.cs b/WinUIGallery/Helpers/SettingsHelper.cs index 12be0453e..5405b56fd 100644 --- a/WinUIGallery/Helpers/SettingsHelper.cs +++ b/WinUIGallery/Helpers/SettingsHelper.cs @@ -120,7 +120,7 @@ public static bool TryRemoveItem(string key, string item) /// key does not exist or the stored value is null. public static List GetList(string key) { - string raw = appData.LocalSettings.Values[key] as string; + string? raw = appData.LocalSettings.Values[key] as string; return raw != null ? raw.Split(delimiter, StringSplitOptions.RemoveEmptyEntries).ToList() : new List(); @@ -135,7 +135,7 @@ public static List GetList(string key) /// langword="false"/>. public static bool Contains(string key, string item) { - string raw = appData.LocalSettings.Values[key] as string; + string? raw = appData.LocalSettings.Values[key] as string; if (string.IsNullOrEmpty(raw)) return false; @@ -163,7 +163,7 @@ public static void Delete(string key) /// . public static bool Exists(string key) { - string raw = appData.LocalSettings.Values[key] as string; + string? raw = appData.LocalSettings.Values[key] as string; return !string.IsNullOrEmpty(raw); } diff --git a/WinUIGallery/Helpers/SuspensionManager.cs b/WinUIGallery/Helpers/SuspensionManager.cs index a540cec5d..5cf54abc9 100644 --- a/WinUIGallery/Helpers/SuspensionManager.cs +++ b/WinUIGallery/Helpers/SuspensionManager.cs @@ -66,7 +66,7 @@ public static async Task SaveAsync() // Save the navigation state for all registered frames foreach (var weakFrameReference in _registeredFrames) { - if (weakFrameReference.TryGetTarget(out Frame frame)) + if (weakFrameReference.TryGetTarget(out Frame? frame)) { SaveFrameNavigationState(frame); } @@ -119,13 +119,17 @@ public static async Task RestoreAsync() { // Deserialize the Session State DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary), _knownTypes); - _sessionState = (Dictionary)serializer.ReadObject(inStream.AsStreamForRead()); + + if (serializer.ReadObject(inStream.AsStreamForRead()) is Dictionary readObject) + { + _sessionState = readObject; + } } // Restore any registered frames to their saved state foreach (var weakFrameReference in _registeredFrames) { - if (weakFrameReference.TryGetTarget(out Frame frame)) + if (weakFrameReference.TryGetTarget(out Frame? frame)) { frame.ClearValue(FrameSessionStateProperty); RestoreFrameNavigationState(frame); @@ -191,7 +195,7 @@ public static void UnregisterFrame(Frame frame) SessionState.Remove((string)frame.GetValue(FrameSessionStateKeyProperty)); _registeredFrames.RemoveAll((weakFrameReference) => { - return !weakFrameReference.TryGetTarget(out Frame testFrame) || testFrame == frame; + return !weakFrameReference.TryGetTarget(out Frame? testFrame) || testFrame == frame; }); } diff --git a/WinUIGallery/Helpers/TabViewHelper.cs b/WinUIGallery/Helpers/TabViewHelper.cs index 349bb25b1..ee688585d 100644 --- a/WinUIGallery/Helpers/TabViewHelper.cs +++ b/WinUIGallery/Helpers/TabViewHelper.cs @@ -19,8 +19,8 @@ public static void PopulateTabViewContextMenu(MenuFlyout menuFlyout) { return; } - ListView tabViewListView = null; - TabView tabView = null; + ListView? tabViewListView = null; + TabView? tabView = null; DependencyObject current = item; diff --git a/WinUIGallery/Helpers/ThemeHelper.cs b/WinUIGallery/Helpers/ThemeHelper.cs index 161043dfc..bb718787b 100644 --- a/WinUIGallery/Helpers/ThemeHelper.cs +++ b/WinUIGallery/Helpers/ThemeHelper.cs @@ -74,7 +74,7 @@ public static void Initialize() { if (NativeMethods.IsAppPackaged) { - string savedTheme = appData.LocalSettings.Values[SettingsKeys.SelectedAppTheme]?.ToString(); + string? savedTheme = appData.LocalSettings.Values[SettingsKeys.SelectedAppTheme]?.ToString(); if (savedTheme != null) { diff --git a/WinUIGallery/Helpers/UIHelper.cs b/WinUIGallery/Helpers/UIHelper.cs index dc4cd33f1..f4f1130ce 100644 --- a/WinUIGallery/Helpers/UIHelper.cs +++ b/WinUIGallery/Helpers/UIHelper.cs @@ -46,11 +46,11 @@ public static IEnumerable GetDescendants(this DependencyObject } } - static public UIElement FindElementByName(UIElement element, string name) + static public UIElement? FindElementByName(UIElement element, string name) { if (element.XamlRoot != null && element.XamlRoot.Content != null) { - var ele = (element.XamlRoot.Content as FrameworkElement).FindName(name); + var ele = (element.XamlRoot.Content as FrameworkElement)?.FindName(name); if (ele != null) { return ele as UIElement; diff --git a/WinUIGallery/Helpers/Win32WindowHelper.cs b/WinUIGallery/Helpers/Win32WindowHelper.cs index 9b94d8658..adc6f55f8 100644 --- a/WinUIGallery/Helpers/Win32WindowHelper.cs +++ b/WinUIGallery/Helpers/Win32WindowHelper.cs @@ -9,7 +9,7 @@ namespace WinUIGallery.Helpers; internal partial class Win32WindowHelper { - private static WinProc newWndProc = null; + private static WinProc? newWndProc = null; private static nint oldWndProc = nint.Zero; private POINT? minWindowSize = null; diff --git a/WinUIGallery/Helpers/WindowHelper.cs b/WinUIGallery/Helpers/WindowHelper.cs index a3d6c6a07..667d79cd9 100644 --- a/WinUIGallery/Helpers/WindowHelper.cs +++ b/WinUIGallery/Helpers/WindowHelper.cs @@ -33,7 +33,7 @@ static public void TrackWindow(Window window) _activeWindows.Add(window); } - static public Window GetWindowForElement(UIElement element) + static public Window? GetWindowForElement(UIElement element) { if (element.XamlRoot != null) { diff --git a/WinUIGallery/Layouts/ActivityFeedLayout.cs b/WinUIGallery/Layouts/ActivityFeedLayout.cs index 874849bc5..832656e65 100644 --- a/WinUIGallery/Layouts/ActivityFeedLayout.cs +++ b/WinUIGallery/Layouts/ActivityFeedLayout.cs @@ -67,7 +67,11 @@ public Size MinItemSize private static void OnPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { - var layout = obj as ActivityFeedLayout; + if (obj is not ActivityFeedLayout layout) + { + return; + } + if (args.Property == RowSpacingProperty) { layout._rowSpacing = (double)args.NewValue; @@ -138,7 +142,11 @@ protected override Size MeasureOverride(VirtualizingLayoutContext context, Size context.ItemCount / 3); // Determine which items will appear on those rows and what the rect will be for each item - var state = context.LayoutState as ActivityFeedLayoutState; + if (context.LayoutState is not ActivityFeedLayoutState state) + { + throw new InvalidOperationException("LayoutState is not of type ActivityFeedLayoutState"); + } + state.LayoutRects.Clear(); // Save the index of the first realized item. We'll use it as a starting point during arrange. @@ -188,7 +196,11 @@ protected override Size MeasureOverride(VirtualizingLayoutContext context, Size protected override Size ArrangeOverride(VirtualizingLayoutContext context, Size finalSize) { // walk through the cache of containers and arrange - var state = context.LayoutState as ActivityFeedLayoutState; + if (context.LayoutState is not ActivityFeedLayoutState state) + { + throw new InvalidOperationException("LayoutState is not of type ActivityFeedLayoutState"); + } + var virtualContext = context as VirtualizingLayoutContext; int currentIndex = state.FirstRealizedIndex; @@ -265,5 +277,5 @@ public List LayoutRects } } - private List _layoutRects; + private List? _layoutRects; } diff --git a/WinUIGallery/MainWindow.xaml.cs b/WinUIGallery/MainWindow.xaml.cs index 0dda5d96e..2cbe63724 100644 --- a/WinUIGallery/MainWindow.xaml.cs +++ b/WinUIGallery/MainWindow.xaml.cs @@ -30,7 +30,7 @@ public NavigationView NavigationView get { return NavigationViewControl; } } - public Action NavigationViewLoaded { get; set; } + public Action? NavigationViewLoaded { get; set; } public MainWindow() { @@ -110,7 +110,7 @@ void OnNavigationFailed(object sender, NavigationFailedEventArgs e) // Wraps a call to rootFrame.Navigate to give the Page a way to know which NavigationRootPage is navigating. // Please call this function rather than rootFrame.Navigate to navigate the rootFrame. - public void Navigate(Type pageType, object targetPageArguments = null, NavigationTransitionInfo navigationTransitionInfo = null) + public void Navigate(Type pageType, object? targetPageArguments = null, NavigationTransitionInfo? navigationTransitionInfo = null) { rootFrame.Navigate(pageType, targetPageArguments, navigationTransitionInfo); @@ -118,7 +118,7 @@ public void Navigate(Type pageType, object targetPageArguments = null, Navigatio if (pageType.Equals(typeof(ItemPage)) && targetPageArguments != null) { // Mark the item sample's page visited - SettingsHelper.TryAddItem(SettingsKeys.RecentlyVisited, targetPageArguments.ToString(), InsertPosition.First, SettingsHelper.MaxRecentlyVisitedSamples); + SettingsHelper.TryAddItem(SettingsKeys.RecentlyVisited, targetPageArguments.ToString() ?? string.Empty, InsertPosition.First, SettingsHelper.MaxRecentlyVisitedSamples); } } @@ -196,7 +196,7 @@ public void AddNavigationMenuItems() private void OnMenuFlyoutItemClick(object sender, RoutedEventArgs e) { - switch ((sender as MenuFlyoutItem).Tag) + switch ((sender as MenuFlyoutItem)?.Tag) { case ControlInfoDataItem item: ProtocolActivationClipboardHelper.Copy(item); @@ -231,12 +231,16 @@ private void OnNavigationViewControlLoaded(object sender, RoutedEventArgs e) Task.Delay(500).ContinueWith(_ => this.NavigationViewLoaded?.Invoke(), TaskScheduler.FromCurrentSynchronizationContext()); var navigationView = sender as NavigationView; - navigationView.RegisterPropertyChangedCallback(NavigationView.IsPaneOpenProperty, OnIsPaneOpenChanged); + navigationView?.RegisterPropertyChangedCallback(NavigationView.IsPaneOpenProperty, OnIsPaneOpenChanged); } private void OnIsPaneOpenChanged(DependencyObject sender, DependencyProperty dp) { - var navigationView = sender as NavigationView; + if (sender is not NavigationView navigationView) + { + return; + } + var announcementText = navigationView.IsPaneOpen ? "Navigation Pane Opened" : "Navigation Pane Closed"; UIHelper.AnnounceActionForAccessibility(navigationView, announcementText, "NavigationViewPaneIsOpenChangeNotificationId"); @@ -395,9 +399,8 @@ private void OnControlsSearchBoxTextChanged(AutoSuggestBox sender, AutoSuggestBo private void OnControlsSearchBoxQuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args) { - if (args.ChosenSuggestion != null && args.ChosenSuggestion is ControlInfoDataItem) + if (args.ChosenSuggestion is ControlInfoDataItem infoDataItem) { - var infoDataItem = args.ChosenSuggestion as ControlInfoDataItem; var hasChangedSelection = EnsureItemIsVisibleInNavigation(infoDataItem.Title); // In case the menu selection has changed, it means that it has triggered @@ -419,14 +422,12 @@ public bool EnsureItemIsVisibleInNavigation(string name) foreach (object rawItem in NavigationView.MenuItems) { // Check if we encountered the separator - if (!(rawItem is NavigationViewItem)) + if (rawItem is not NavigationViewItem item) { // Skipping this item continue; } - var item = rawItem as NavigationViewItem; - // Check if we are this category if ((string)item.Content == name) { diff --git a/WinUIGallery/Models/Category.cs b/WinUIGallery/Models/Category.cs index ab51c833e..7103755cf 100644 --- a/WinUIGallery/Models/Category.cs +++ b/WinUIGallery/Models/Category.cs @@ -8,8 +8,8 @@ public partial class CategoryBase { } public partial class Category : CategoryBase { - public string Name { get; set; } - public string Tooltip { get; set; } + public string Name { get; set; } = string.Empty; + public string Tooltip { get; set; } = string.Empty; public Symbol Glyph { get; set; } } @@ -17,5 +17,5 @@ public partial class Separator : CategoryBase { } public partial class Header : CategoryBase { - public string Name { get; set; } + public string Name { get; set; } = string.Empty; } diff --git a/WinUIGallery/Models/ControlInfoData.cs b/WinUIGallery/Models/ControlInfoData.cs index 7f29bd92a..8d0324134 100644 --- a/WinUIGallery/Models/ControlInfoData.cs +++ b/WinUIGallery/Models/ControlInfoData.cs @@ -16,7 +16,7 @@ namespace WinUIGallery.Models; public partial class Root { - public ObservableCollection Groups { get; set; } + public ObservableCollection Groups { get; set; } = []; } [JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true)] [JsonSerializable(typeof(Root))] @@ -29,22 +29,22 @@ internal partial class RootContext : JsonSerializerContext /// public partial class ControlInfoDataItem { - public string UniqueId { get; set; } - public string Title { get; set; } - public string[] BaseClasses { get; set; } - public string ApiNamespace { get; set; } - public string Subtitle { get; set; } - public string Description { get; set; } - public string ImagePath { get; set; } - public string BadgeString { get; set; } + public string UniqueId { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public string[] BaseClasses { get; set; } = []; + public string ApiNamespace { get; set; } = string.Empty; + public string Subtitle { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public string ImagePath { get; set; } = string.Empty; + public string BadgeString { get; set; } = string.Empty; public bool IsNew { get; set; } public bool IsUpdated { get; set; } public bool IsPreview { get; set; } - public ObservableCollection Docs { get; set; } + public ObservableCollection Docs { get; set; } = []; public bool IncludedInBuild { get; set; } - public string SourcePath { get; set; } + public string SourcePath { get; set; } = string.Empty; public override string ToString() { @@ -54,8 +54,8 @@ public override string ToString() public partial class ControlInfoDocLink { - public string Title { get; set; } - public string Uri { get; set; } + public string Title { get; set; } = string.Empty; + public string Uri { get; set; } = string.Empty; } @@ -65,12 +65,12 @@ public partial class ControlInfoDocLink [WinRT.GeneratedBindableCustomPropertyAttribute] public partial class ControlInfoDataGroup { - public string UniqueId { get; set; } - public string Title { get; set; } - public string IconGlyph { get; set; } + public string UniqueId { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public string IconGlyph { get; set; } = string.Empty; public bool IsSpecialSection { get; set; } - public string Folder { get; set; } - public ObservableCollection Items { get; set; } + public string Folder { get; set; } = string.Empty; + public ObservableCollection Items { get; set; } = []; public override string ToString() { diff --git a/WinUIGallery/Models/IconData.cs b/WinUIGallery/Models/IconData.cs index 4bfb9ce3e..abdd3a9b7 100644 --- a/WinUIGallery/Models/IconData.cs +++ b/WinUIGallery/Models/IconData.cs @@ -10,8 +10,8 @@ namespace WinUIGallery.Models; public partial class IconData { - public string Name { get; set; } - public string Code { get; set; } + public string Name { get; set; } = string.Empty; + public string Code { get; set; } = string.Empty; public string[] Tags { get; set; } = []; public bool IsSegoeFluentOnly { get; set; } @@ -19,7 +19,7 @@ public partial class IconData public string CodeGlyph => "\\u" + Code; public string TextGlyph => "&#x" + Code + ";"; - public string SymbolName => Enum.TryParse(Name, out var symbol) ? symbol.ToString() : null; + public string? SymbolName => Enum.TryParse(Name, out var symbol) ? symbol.ToString() : null; } [JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true)] [JsonSerializable(typeof(List))] diff --git a/WinUIGallery/Pages/HomePage.xaml.cs b/WinUIGallery/Pages/HomePage.xaml.cs index 19e622252..7dd185b33 100644 --- a/WinUIGallery/Pages/HomePage.xaml.cs +++ b/WinUIGallery/Pages/HomePage.xaml.cs @@ -13,9 +13,9 @@ namespace WinUIGallery.Pages; public sealed partial class HomePage : ItemsPageBase { - IReadOnlyList RecentlyVisitedSamplesList; - IReadOnlyList RecentlyAddedOrUpdatedSamplesList; - IReadOnlyList FavoriteSamplesList; + IReadOnlyList? RecentlyVisitedSamplesList; + IReadOnlyList? RecentlyAddedOrUpdatedSamplesList; + IReadOnlyList? FavoriteSamplesList; public HomePage() { @@ -43,7 +43,7 @@ public List GetValidItems(string settingsKey) { List keyList = SettingsHelper.GetList(settingsKey); - if (keyList == null || keyList.Count == 0) + if (keyList.Count == 0 || Items is null) return new List(); Dictionary itemMap = Items.ToDictionary(i => i.UniqueId); diff --git a/WinUIGallery/Pages/ItemPage.xaml.cs b/WinUIGallery/Pages/ItemPage.xaml.cs index ec1f079c1..c47efab24 100644 --- a/WinUIGallery/Pages/ItemPage.xaml.cs +++ b/WinUIGallery/Pages/ItemPage.xaml.cs @@ -21,13 +21,13 @@ public sealed partial class ItemPage : Page private static string WinUIBaseUrl = "https://github.com/microsoft/microsoft-ui-xaml/tree/main/src/controls/dev"; private static string GalleryBaseUrl = "https://github.com/microsoft/WinUI-Gallery/tree/main/WinUIGallery/Samples/ControlPages/"; - public ControlInfoDataItem Item + public ControlInfoDataItem? Item { get { return _item; } set { _item = value; } } - private ControlInfoDataItem _item; + private ControlInfoDataItem? _item; private ElementTheme? _currentElementTheme; public ItemPage() @@ -45,7 +45,10 @@ public void SetInitialVisuals() private void OnNavigationViewLoaded() { - App.MainWindow.EnsureNavigationSelection(this.Item.UniqueId); + if (this.Item is not null) + { + App.MainWindow.EnsureNavigationSelection(this.Item.UniqueId); + } } protected override async void OnNavigatedTo(NavigationEventArgs e) @@ -60,17 +63,17 @@ protected override async void OnNavigatedTo(NavigationEventArgs e) Item = item; // Load control page into frame. - Type pageType = Type.GetType("WinUIGallery.ControlPages." + item.UniqueId + "Page"); + Type? pageType = Type.GetType("WinUIGallery.ControlPages." + item.UniqueId + "Page"); if (pageType != null) { - var pageName = string.IsNullOrEmpty(group.Folder) ? pageType.Name : $"{group.Folder}/{pageType.Name}"; + var pageName = string.IsNullOrEmpty(group?.Folder) ? pageType.Name : $"{group.Folder}/{pageType.Name}"; pageHeader.SetControlSourceLink(WinUIBaseUrl, item.SourcePath); pageHeader.SetSamplePageSourceLinks(GalleryBaseUrl, pageName); System.Diagnostics.Debug.WriteLine(string.Format("[ItemPage] Navigate to {0}", pageType.ToString())); this.contentFrame.Navigate(pageType); } - App.MainWindow.EnsureNavigationSelection(item?.UniqueId); + App.MainWindow.EnsureNavigationSelection(item.UniqueId); if (contentFrame.Content is Page loadedPage && PageScrollBehaviorHelper.GetSuppressHostScrolling(loadedPage)) { @@ -97,21 +100,21 @@ protected override void OnNavigatedFrom(NavigationEventArgs e) // We use reflection to call the OnNavigatedFrom function the user leaves this page // See this PR for more information: https://github.com/microsoft/WinUI-Gallery/pull/145 Frame contentFrameAsFrame = contentFrame as Frame; - Page innerPage = contentFrameAsFrame.Content as Page; + Page? innerPage = contentFrameAsFrame.Content as Page; if (innerPage != null) { - MethodInfo dynMethod = innerPage.GetType().GetMethod("OnNavigatedFrom", + MethodInfo? dynMethod = innerPage.GetType().GetMethod("OnNavigatedFrom", BindingFlags.NonPublic | BindingFlags.Instance); - dynMethod.Invoke(innerPage, new object[] { e }); + dynMethod?.Invoke(innerPage, new object[] { e }); } base.OnNavigatedFrom(e); } - public static ItemPage GetForElement(object obj) + public static ItemPage? GetForElement(object obj) { UIElement element = (UIElement)obj; - Window window = WindowHelper.GetWindowForElement(element); + Window? window = WindowHelper.GetWindowForElement(element); if (window != null) { return (ItemPage)window.Content; @@ -121,7 +124,7 @@ public static ItemPage GetForElement(object obj) private void OnToggleTheme() { - var currentElementTheme = ((_currentElementTheme ?? ElementTheme.Default) == ElementTheme.Default) ? ThemeHelper.ActualTheme : _currentElementTheme.Value; + var currentElementTheme = ((_currentElementTheme ?? ElementTheme.Default) == ElementTheme.Default) ? ThemeHelper.ActualTheme : _currentElementTheme; var newTheme = currentElementTheme == ElementTheme.Dark ? ElementTheme.Light : ElementTheme.Dark; SetControlExamplesTheme(newTheme); } diff --git a/WinUIGallery/Pages/ItemsPageBase.cs b/WinUIGallery/Pages/ItemsPageBase.cs index c76fa0ea0..ed383d17b 100644 --- a/WinUIGallery/Pages/ItemsPageBase.cs +++ b/WinUIGallery/Pages/ItemsPageBase.cs @@ -15,12 +15,12 @@ namespace WinUIGallery.Pages; public abstract class ItemsPageBase : Page, INotifyPropertyChanged { - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; - private string _itemId; - private IEnumerable _items; + private string? _itemId; + private IEnumerable? _items; - public IEnumerable Items + public IEnumerable? Items { get { return _items; } set { SetProperty(ref _items, value); } @@ -72,7 +72,7 @@ protected void OnItemGridViewLoaded(object sender, RoutedEventArgs e) } } - protected bool SetProperty(ref T storage, T value, [CallerMemberName] string propertyName = null) + protected bool SetProperty(ref T storage, T value, [CallerMemberName] string? propertyName = null) { if (Equals(storage, value)) return false; @@ -81,7 +81,7 @@ protected bool SetProperty(ref T storage, T value, [CallerMemberName] string return true; } - protected void NotifyPropertyChanged([CallerMemberName] string propertyName = null) + protected void NotifyPropertyChanged([CallerMemberName] string? propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } diff --git a/WinUIGallery/Pages/SearchResultsPage.xaml.cs b/WinUIGallery/Pages/SearchResultsPage.xaml.cs index b22aa70e9..ee24b61c1 100644 --- a/WinUIGallery/Pages/SearchResultsPage.xaml.cs +++ b/WinUIGallery/Pages/SearchResultsPage.xaml.cs @@ -19,11 +19,11 @@ namespace WinUIGallery.Pages; /// public sealed partial class SearchResultsPage : ItemsPageBase { - private IEnumerable _filters; - private Filter _selectedFilter; - string _queryText; + private IEnumerable? _filters; + private Filter? _selectedFilter; + string _queryText = string.Empty; - public IEnumerable Filters + public IEnumerable? Filters { get { return _filters; } set { this.SetProperty(ref _filters, value); } @@ -143,10 +143,10 @@ protected override bool GetIsNarrowLayoutState() /// public sealed partial class Filter : INotifyPropertyChanged { - private string _name; + private string _name = string.Empty; private int _count; private bool? _active; - private List _items; + private List _items = []; public Filter(string name, int count, List controlInfoList, bool active = false) { @@ -193,7 +193,7 @@ public string Description /// /// Multicast event for property change notifications. /// - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; /// /// Checks if a property already matches a desired value. Sets the property and @@ -207,7 +207,7 @@ public string Description /// support CallerMemberName. /// True if the value was changed, false if the existing value matched the /// desired value. - private bool SetProperty(ref T storage, T value, [CallerMemberName] string propertyName = null) + private bool SetProperty(ref T storage, T value, [CallerMemberName] string? propertyName = null) { if (object.Equals(storage, value)) return false; @@ -222,7 +222,7 @@ private bool SetProperty(ref T storage, T value, [CallerMemberName] string pr /// Name of the property used to notify listeners. This /// value is optional and can be provided automatically when invoked from compilers /// that support . - private void NotifyPropertyChanged([CallerMemberName] string propertyName = null) + private void NotifyPropertyChanged([CallerMemberName] string? propertyName = null) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } diff --git a/WinUIGallery/Pages/SectionPage.xaml.cs b/WinUIGallery/Pages/SectionPage.xaml.cs index cab402aba..54e6b62c5 100644 --- a/WinUIGallery/Pages/SectionPage.xaml.cs +++ b/WinUIGallery/Pages/SectionPage.xaml.cs @@ -5,6 +5,7 @@ using Microsoft.UI.Xaml.Navigation; using System.Linq; using WinUIGallery.Helpers; +using WinUIGallery.Models; namespace WinUIGallery.Pages; @@ -23,10 +24,9 @@ protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); - if (e.Parameter is string groupID) + if (e.Parameter is string groupID && + await ControlInfoDataSource.GetGroupAsync(groupID) is ControlInfoDataGroup group) { - var group = await ControlInfoDataSource.GetGroupAsync(groupID); - ((NavigationViewItemBase)App.MainWindow.NavigationView.MenuItems.Single(i => (string)((NavigationViewItemBase)i).Tag == group.UniqueId)).IsSelected = true; TitleTxt.Text = group.Title; Items = group.Items.OrderBy(i => i.Title).ToList(); diff --git a/WinUIGallery/Pages/SettingsPage.xaml.cs b/WinUIGallery/Pages/SettingsPage.xaml.cs index fb376043f..54f724fe2 100644 --- a/WinUIGallery/Pages/SettingsPage.xaml.cs +++ b/WinUIGallery/Pages/SettingsPage.xaml.cs @@ -22,8 +22,9 @@ public string Version { get { - var version = ProcessInfoHelper.GetVersion(); - return string.Format("{0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision); + return ProcessInfoHelper.GetVersion() is Version version + ? string.Format("{0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision) + : string.Empty; } } @@ -82,19 +83,23 @@ private void OnSettingsPageLoaded(object sender, RoutedEventArgs e) } private void themeMode_SelectionChanged(object sender, RoutedEventArgs e) - { - var selectedTheme = ((ComboBoxItem)themeMode.SelectedItem)?.Tag?.ToString(); - var window = WindowHelper.GetWindowForElement(this); - if (selectedTheme != null) - { - ThemeHelper.RootTheme = EnumHelper.GetEnum(selectedTheme); - var elementThemeResolved = ThemeHelper.RootTheme == ElementTheme.Default ? ThemeHelper.ActualTheme : ThemeHelper.RootTheme; - TitleBarHelper.ApplySystemThemeToCaptionButtons(window, elementThemeResolved); - - // announce visual change to automation - UIHelper.AnnounceActionForAccessibility(sender as UIElement, $"Theme changed to {elementThemeResolved}", - "ThemeChangedNotificationActivityId"); - } + { + if (sender is not UIElement senderUiLement || + (themeMode.SelectedItem as ComboBoxItem)?.Tag.ToString() is not string selectedTheme || + WindowHelper.GetWindowForElement(this) is not Window window) + { + return; + } + + ThemeHelper.RootTheme = EnumHelper.GetEnum(selectedTheme); + var elementThemeResolved = ThemeHelper.RootTheme == ElementTheme.Default ? ThemeHelper.ActualTheme : ThemeHelper.RootTheme; + TitleBarHelper.ApplySystemThemeToCaptionButtons(window, elementThemeResolved); + + // announce visual change to automation + UIHelper.AnnounceActionForAccessibility( + senderUiLement, + $"Theme changed to {elementThemeResolved}", + "ThemeChangedNotificationActivityId"); } private void soundToggle_Toggled(object sender, RoutedEventArgs e) diff --git a/WinUIGallery/Samples/ControlPages/AnimatedIconPage.xaml.cs b/WinUIGallery/Samples/ControlPages/AnimatedIconPage.xaml.cs index 0ca798114..516f59a69 100644 --- a/WinUIGallery/Samples/ControlPages/AnimatedIconPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/AnimatedIconPage.xaml.cs @@ -4,6 +4,7 @@ using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Controls.AnimatedVisuals; using Microsoft.UI.Xaml.Input; +using System; namespace WinUIGallery.ControlPages; @@ -36,7 +37,8 @@ public static IAnimatedVisualSource2 GetAnimationSourceFromString(object selecti case "AnimatedFindVisualSource": return new AnimatedFindVisualSource(); case "AnimatedGlobalNavigationButtonVisualSource": return new AnimatedGlobalNavigationButtonVisualSource(); case "AnimatedSettingsVisualSource": return new AnimatedSettingsVisualSource(); - default: return null; + // Throw an exception if the name is not recognized. + default: throw new InvalidOperationException($"{name} is not a valid animated visual."); } } } diff --git a/WinUIGallery/Samples/ControlPages/AnimatedVisualPlayerPage.xaml.cs b/WinUIGallery/Samples/ControlPages/AnimatedVisualPlayerPage.xaml.cs index 2a2cd3a37..d7e1450e3 100644 --- a/WinUIGallery/Samples/ControlPages/AnimatedVisualPlayerPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/AnimatedVisualPlayerPage.xaml.cs @@ -51,7 +51,7 @@ private void ReverseButton_Click(object sender, RoutedEventArgs e) private void EnsurePlaying() { - if (PauseButton.IsChecked.Value) + if (PauseButton.IsChecked is true) { // Resume playing the animation, if paused. PauseButton.IsChecked = false; diff --git a/WinUIGallery/Samples/ControlPages/AnnotatedScrollBarPage.xaml.cs b/WinUIGallery/Samples/ControlPages/AnnotatedScrollBarPage.xaml.cs index 36c8d7055..0fc9f1800 100644 --- a/WinUIGallery/Samples/ControlPages/AnnotatedScrollBarPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/AnnotatedScrollBarPage.xaml.cs @@ -57,11 +57,12 @@ private void ItemsRepeater_SizeChanged(object sender, Microsoft.UI.Xaml.SizeChan private void AnnotatedScrollBarMaxHeightSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e) { - if (annotatedScrollBar != null) + if (sender is Slider slider && + annotatedScrollBar != null) { // Changing the height of the AnnotatedScrollBar to illustrate how labels // are hidden to avoid collisions when the available room shrinks too much. - annotatedScrollBar.MaxHeight = (sender as Slider).Value; + annotatedScrollBar.MaxHeight = slider.Value; } } diff --git a/WinUIGallery/Samples/ControlPages/AppWindowPage.xaml.cs b/WinUIGallery/Samples/ControlPages/AppWindowPage.xaml.cs index 77ed768ef..39442ad54 100644 --- a/WinUIGallery/Samples/ControlPages/AppWindowPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/AppWindowPage.xaml.cs @@ -88,7 +88,7 @@ private void InitialSize_SelectionChanged(object sender, SelectionChangedEventAr return; } - string size = InitialSize.SelectedItem.ToString(); + string size = InitialSize.SelectedItem.ToString() ?? "Unknown"; string percentage = size switch { "Small" => "5%", diff --git a/WinUIGallery/Samples/ControlPages/AutoSuggestBoxPage.xaml.cs b/WinUIGallery/Samples/ControlPages/AutoSuggestBoxPage.xaml.cs index 0f204b429..e1b6d8971 100644 --- a/WinUIGallery/Samples/ControlPages/AutoSuggestBoxPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/AutoSuggestBoxPage.xaml.cs @@ -185,18 +185,18 @@ private void Control2_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChang /// and also ChosenSuggestion, which is only non-null when a user selects an item in the list. private void Control2_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args) { - if (args.ChosenSuggestion != null && args.ChosenSuggestion is ControlInfoDataItem) + if (args.ChosenSuggestion is ControlInfoDataItem chosenSuggestion) { //User selected an item, take an action - SelectControl(args.ChosenSuggestion as ControlInfoDataItem); + SelectControl(chosenSuggestion); } else if (!string.IsNullOrEmpty(args.QueryText)) { //Do a fuzzy search based on the text var suggestions = SearchControls(sender.Text); - if (suggestions.Count > 0) + if (suggestions.FirstOrDefault() is ControlInfoDataItem firstItem) { - SelectControl(suggestions.FirstOrDefault()); + SelectControl(firstItem); } } } @@ -228,7 +228,7 @@ private void SelectControl(ControlInfoDataItem control) ControlDetails.Visibility = Visibility.Visible; - BitmapImage image = control.ImagePath == null ? null : new BitmapImage(new Uri(control.ImagePath)); + BitmapImage? image = control.ImagePath == null ? null : new BitmapImage(new Uri(control.ImagePath)); ControlImage.Source = image; ControlTitle.Text = control.Title; diff --git a/WinUIGallery/Samples/ControlPages/BorderPage.xaml.cs b/WinUIGallery/Samples/ControlPages/BorderPage.xaml.cs index bdbbdfd20..0f017a323 100644 --- a/WinUIGallery/Samples/ControlPages/BorderPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/BorderPage.xaml.cs @@ -25,7 +25,7 @@ private void BGRadioButton_Checked(object sender, RoutedEventArgs e) { if (sender is RadioButton rb && Control1 != null) { - string colorName = rb.Content.ToString(); + string? colorName = rb.Content.ToString(); switch (colorName) { case "Yellow": @@ -48,7 +48,7 @@ private void RadioButton_Checked(object sender, RoutedEventArgs e) { if (sender is RadioButton rb && Control1 != null) { - string colorName = rb.Content.ToString(); + string? colorName = rb.Content.ToString(); switch (colorName) { case "Yellow": diff --git a/WinUIGallery/Samples/ControlPages/BreadcrumbBarPage.xaml.cs b/WinUIGallery/Samples/ControlPages/BreadcrumbBarPage.xaml.cs index ba7615bea..5b13ec7b3 100644 --- a/WinUIGallery/Samples/ControlPages/BreadcrumbBarPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/BreadcrumbBarPage.xaml.cs @@ -37,7 +37,11 @@ public BreadcrumbBarPage() private void BreadcrumbBar2_ItemClicked(BreadcrumbBar sender, BreadcrumbBarItemClickedEventArgs args) { - var items = BreadcrumbBar2.ItemsSource as ObservableCollection; + if (BreadcrumbBar2.ItemsSource is not ObservableCollection items) + { + return; + } + for (int i = items.Count - 1; i >= args.Index + 1; i--) { items.RemoveAt(i); @@ -49,7 +53,11 @@ private void ResetSampleButton_Click(object sender, Microsoft.UI.Xaml.RoutedEven // To restore the BreadcrumbBar to its initial state, we compare Folders (the live collection) // with _defaultFolders (the original state), and add back any missing items. // This ensures reset works even after user navigation modifies the ItemsSource. - var items = BreadcrumbBar2.ItemsSource as ObservableCollection; + if (BreadcrumbBar2.ItemsSource is not ObservableCollection items) + { + return; + } + foreach (var folder in _defaultFolders) { if (!items.Contains(folder)) @@ -66,5 +74,5 @@ private void ResetSampleButton_Click(object sender, Microsoft.UI.Xaml.RoutedEven public class Folder { - public string Name { get; set; } + public string Name { get; set; } = string.Empty; } diff --git a/WinUIGallery/Samples/ControlPages/CalendarViewPage.xaml.cs b/WinUIGallery/Samples/ControlPages/CalendarViewPage.xaml.cs index 5b8d64079..5137836d7 100644 --- a/WinUIGallery/Samples/ControlPages/CalendarViewPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/CalendarViewPage.xaml.cs @@ -38,7 +38,7 @@ public CalendarViewPage() private void SelectionMode_SelectionChanged(object sender, SelectionChangedEventArgs e) { - if (Enum.TryParse((sender as ComboBox).SelectedItem.ToString(), out CalendarViewSelectionMode selectionMode)) + if (Enum.TryParse((sender as ComboBox)?.SelectedItem.ToString(), out CalendarViewSelectionMode selectionMode)) { Control1.SelectionMode = selectionMode; } @@ -46,8 +46,8 @@ private void SelectionMode_SelectionChanged(object sender, SelectionChangedEvent private void calendarLanguages_SelectionChanged(object sender, SelectionChangedEventArgs e) { - var selectedLang = calendarLanguages.SelectedItem as Language; - if (Windows.Globalization.Language.IsWellFormed(selectedLang.Code) && selectedLang != null) + if (calendarLanguages.SelectedItem is Language selectedLang && + Windows.Globalization.Language.IsWellFormed(selectedLang.Code)) { Control1.Language = selectedLang.Code; } diff --git a/WinUIGallery/Samples/ControlPages/CaptureElementPreviewPage.xaml.cs b/WinUIGallery/Samples/ControlPages/CaptureElementPreviewPage.xaml.cs index 57141b334..ea0c24abc 100644 --- a/WinUIGallery/Samples/ControlPages/CaptureElementPreviewPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/CaptureElementPreviewPage.xaml.cs @@ -83,8 +83,8 @@ private void CaptureElementPreviewPage_Unloaded(object sender, RoutedEventArgs e } } - private MediaFrameSourceGroup mediaFrameSourceGroup; - private MediaCapture mediaCapture; + private MediaFrameSourceGroup? mediaFrameSourceGroup; + private MediaCapture? mediaCapture; private async Task StartCaptureElement() { @@ -114,7 +114,7 @@ private async Task StartCaptureElement() public string MirrorTextReplacement = ""; // starts not mirrored, so no text in that case - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; public void OnPropertyChanged(string PropertyName) { @@ -143,6 +143,11 @@ private void MirrorToggleSwitch_Toggled(object sender, RoutedEventArgs e) async private void CapturePhoto_Click(object sender, RoutedEventArgs e) { + if (mediaCapture is null) + { + return; + } + // Capture a photo to a stream var imgFormat = ImageEncodingProperties.CreateJpeg(); var stream = new InMemoryRandomAccessStream(); diff --git a/WinUIGallery/Samples/ControlPages/ClipboardPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ClipboardPage.xaml.cs index 4adae32bf..0a6b07a0a 100644 --- a/WinUIGallery/Samples/ControlPages/ClipboardPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ClipboardPage.xaml.cs @@ -24,12 +24,17 @@ public ClipboardPage() private void CopyText_Click(object sender, RoutedEventArgs args) { + if (sender is not Button button) + { + return; + } + richEditBox.Document.GetText(Microsoft.UI.Text.TextGetOptions.None, out textToCopy); var package = new DataPackage(); package.SetText(textToCopy); Clipboard.SetContent(package); - UIHelper.AnnounceActionForAccessibility(sender as Button, "Text copied to clipboard", "TextCopiedSuccessNotificationId"); + UIHelper.AnnounceActionForAccessibility(button, "Text copied to clipboard", "TextCopiedSuccessNotificationId"); VisualStateManager.GoToState(this, "ConfirmationClipboardVisible", false); Microsoft.UI.Dispatching.DispatcherQueue dispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread(); @@ -48,13 +53,18 @@ private void CopyText_Click(object sender, RoutedEventArgs args) private async void PasteText_Click(object sender, RoutedEventArgs args) { + if (sender is not Button button) + { + return; + } + var package = Clipboard.GetContent(); if (package.Contains(StandardDataFormats.Text)) { var text = await package.GetTextAsync(); PasteClipboard2.Text = text; - UIHelper.AnnounceActionForAccessibility(sender as Button, "Text pasted from clipboard", "TextPastedSuccessNotificationId"); + UIHelper.AnnounceActionForAccessibility(button, "Text pasted from clipboard", "TextPastedSuccessNotificationId"); } } diff --git a/WinUIGallery/Samples/ControlPages/ComboBoxPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ComboBoxPage.xaml.cs index 1b09ea3ba..b01a1b8f4 100644 --- a/WinUIGallery/Samples/ControlPages/ComboBoxPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ComboBoxPage.xaml.cs @@ -38,7 +38,7 @@ public ComboBoxPage() private void ColorComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { - string colorName = e.AddedItems[0].ToString(); + string? colorName = e.AddedItems[0].ToString(); Windows.UI.Color color; switch (colorName) { diff --git a/WinUIGallery/Samples/ControlPages/CommandBarFlyoutPage.xaml.cs b/WinUIGallery/Samples/ControlPages/CommandBarFlyoutPage.xaml.cs index d9bd6ed36..1de584d1e 100644 --- a/WinUIGallery/Samples/ControlPages/CommandBarFlyoutPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/CommandBarFlyoutPage.xaml.cs @@ -17,8 +17,13 @@ public CommandBarFlyoutPage() private void OnElementClicked(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) { + if (sender is not AppBarButton appBarButton) + { + return; + } + // Do custom logic - SelectedOptionText.Text = "You clicked: " + (sender as AppBarButton).Label; + SelectedOptionText.Text = "You clicked: " + appBarButton.Label; } private void ShowMenu(bool isTransient) diff --git a/WinUIGallery/Samples/ControlPages/CommandBarPage.xaml.cs b/WinUIGallery/Samples/ControlPages/CommandBarPage.xaml.cs index 34b8e0bd2..452cf2578 100644 --- a/WinUIGallery/Samples/ControlPages/CommandBarPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/CommandBarPage.xaml.cs @@ -25,7 +25,7 @@ public bool MultipleButtons } } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; public void OnPropertyChanged(string PropertyName) { @@ -52,7 +52,12 @@ private void CloseButton_Click(object sender, RoutedEventArgs e) private void OnElementClicked(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) { - SelectedOptionText.Text = "You clicked: " + (sender as AppBarButton).Label; + if (sender is not AppBarButton appBarButon) + { + return; + } + + SelectedOptionText.Text = "You clicked: " + appBarButon.Label; } private void AddSecondaryCommands_Click(object sender, RoutedEventArgs e) diff --git a/WinUIGallery/Samples/ControlPages/CompactSizingPage.xaml.cs b/WinUIGallery/Samples/ControlPages/CompactSizingPage.xaml.cs index 3e143ba01..7c96dc255 100644 --- a/WinUIGallery/Samples/ControlPages/CompactSizingPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/CompactSizingPage.xaml.cs @@ -27,9 +27,9 @@ private void Standard_Checked(object sender, RoutedEventArgs e) ContentFrame.Navigate(typeof(SampleStandardSizingPage), null, new SuppressNavigationTransitionInfo()); - if (oldPage != null) + if (oldPage != null && + ContentFrame.Content is SampleStandardSizingPage page) { - var page = ContentFrame.Content as SampleStandardSizingPage; page.CopyState(oldPage); } } @@ -40,9 +40,9 @@ private void Compact_Checked(object sender, RoutedEventArgs e) ContentFrame.Navigate(typeof(SampleCompactSizingPage), null, new SuppressNavigationTransitionInfo()); - if (oldPage != null) + if (oldPage != null && + ContentFrame.Content is SampleCompactSizingPage page) { - var page = ContentFrame.Content as SampleCompactSizingPage; page.CopyState(oldPage); } } diff --git a/WinUIGallery/Samples/ControlPages/ConnectedAnimationPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ConnectedAnimationPage.xaml.cs index 2bb437d66..92373704a 100644 --- a/WinUIGallery/Samples/ControlPages/ConnectedAnimationPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ConnectedAnimationPage.xaml.cs @@ -26,14 +26,14 @@ public ConnectedAnimationPage() ContentFrame.Navigate(typeof(SamplePage1)); } - private ConnectedAnimationConfiguration GetConfiguration() + private ConnectedAnimationConfiguration? GetConfiguration() { if (this.ConfigurationPanel == null) { return null; } - var selectedName = (ConfigurationPanel.SelectedItem as RadioButton).Content.ToString(); + string? selectedName = (ConfigurationPanel.SelectedItem as RadioButton)?.Content.ToString(); switch (selectedName) { case "Gravity": @@ -51,14 +51,14 @@ private void NavigateButton_Click(object sender, RoutedEventArgs e) { var currentContent = ContentFrame.Content; - if (currentContent as SamplePage1 != null) + if (currentContent is SamplePage1 samplePage1) { - (currentContent as SamplePage1).PrepareConnectedAnimation(GetConfiguration()); + samplePage1.PrepareConnectedAnimation(GetConfiguration()); ContentFrame.Navigate(typeof(SamplePage2), null, new SuppressNavigationTransitionInfo()); } - else if (currentContent as SamplePage2 != null) + else if (currentContent is SamplePage2 samplePage2) { - (currentContent as SamplePage2).PrepareConnectedAnimation(GetConfiguration()); + samplePage2.PrepareConnectedAnimation(GetConfiguration()); ContentFrame.Navigate(typeof(SamplePage1), null, new SuppressNavigationTransitionInfo()); } } @@ -67,11 +67,11 @@ private void NavigateButton_Click(object sender, RoutedEventArgs e) // Sample data object used to populate the collection page. public class CustomDataObject { - public string Title { get; set; } - public string ImageLocation { get; set; } - public string Views { get; set; } - public string Likes { get; set; } - public string Description { get; set; } + public string Title { get; set; } = string.Empty; + public string ImageLocation { get; set; } = string.Empty; + public string Views { get; set; } = string.Empty; + public string Likes { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; public CustomDataObject() { diff --git a/WinUIGallery/Samples/ControlPages/ContentDialogPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ContentDialogPage.xaml.cs index f065b9405..32c49c197 100644 --- a/WinUIGallery/Samples/ControlPages/ContentDialogPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ContentDialogPage.xaml.cs @@ -35,8 +35,13 @@ private async void ShowDialog_Click(object sender, RoutedEventArgs e) dialog.SecondaryButtonText = "Don't Save"; dialog.CloseButtonText = "Cancel"; dialog.DefaultButton = ContentDialogButton.Primary; - dialog.Content = new ContentDialogContent(); - dialog.RequestedTheme = (VisualTreeHelper.GetParent(sender as Button) as StackPanel).ActualTheme; + dialog.Content = new ContentDialogContent(); + + if (sender is Button button && + VisualTreeHelper.GetParent(button) is StackPanel stackPanel) + { + dialog.RequestedTheme = stackPanel.ActualTheme; + } var result = await dialog.ShowAsync(); @@ -67,7 +72,12 @@ private async void ShowDialogNoDefault_Click(object sender, RoutedEventArgs e) dialog.CloseButtonText = "Cancel"; dialog.DefaultButton = ContentDialogButton.None; dialog.Content = new ContentDialogContent(); - dialog.RequestedTheme = (VisualTreeHelper.GetParent(sender as Button) as StackPanel).ActualTheme; + + if (sender is Button button && + VisualTreeHelper.GetParent(button) is StackPanel stackPanel) + { + dialog.RequestedTheme = stackPanel.ActualTheme; + } var result = await dialog.ShowAsync(); diff --git a/WinUIGallery/Samples/ControlPages/ContentIslandPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ContentIslandPage.xaml.cs index b08841365..84e016178 100644 --- a/WinUIGallery/Samples/ControlPages/ContentIslandPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ContentIslandPage.xaml.cs @@ -21,7 +21,7 @@ public ContentIslandPage() int idx = 0; - Rectangle GetNextHostElement() + Rectangle? GetNextHostElement() { if (idx < _rectanglePanel.Children.Count) { @@ -35,7 +35,7 @@ public async void LoadModel() { ContentIsland parentIsland = this.XamlRoot.ContentIsland; - Rectangle rect = GetNextHostElement(); + Rectangle? rect = GetNextHostElement(); if (rect == null) { return; @@ -48,7 +48,7 @@ public async void LoadModel() // We also need to keep the offset of the ChildContentLink within the parent ContentIsland in sync // with that of the placementElement for UIA to work correctly. - var layoutUpdatedEventHandler = new EventHandler((s, e) => + var layoutUpdatedEventHandler = new EventHandler((s, e) => { // NOTE: Do as little work in here as possible because it gets called for every // xaml layout change on this thread! diff --git a/WinUIGallery/Samples/ControlPages/Design/IconographyPage.xaml.cs b/WinUIGallery/Samples/ControlPages/Design/IconographyPage.xaml.cs index 47fe0ac61..83915d6e5 100644 --- a/WinUIGallery/Samples/ControlPages/Design/IconographyPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/Design/IconographyPage.xaml.cs @@ -24,7 +24,7 @@ public sealed partial class IconographyPage : Page 48 }; - private string currentSearch = null; + private string currentSearch = string.Empty; public IconData SelectedItem { @@ -75,15 +75,20 @@ private void SetSampleCodePresenterCode(IconData value) } else { - XAMLCodePresenterSymbol.Code = null; + XAMLCodePresenterSymbol.Code = string.Empty; - CSharpCodePresenterSymbol.Code = null; + CSharpCodePresenterSymbol.Code = string.Empty; } } private void SearchTextBox_TextChanged(object sender, AutoSuggestBoxTextChangedEventArgs args) { - Filter((sender as AutoSuggestBox).Text); + if (sender is not AutoSuggestBox autoSuggestBox) + { + return; + } + + Filter(autoSuggestBox.Text); } public void Filter(string search) @@ -93,7 +98,7 @@ public void Filter(string search) // Setting current search to trigger breaking condition of other threads currentSearch = search; - string[] filter = search?.Split(" "); + string[] filter = search.Split(" "); // Spawning a new thread to not have the UI freeze because of our search new Thread(() => diff --git a/WinUIGallery/Samples/ControlPages/EasingFunctionPage.xaml.cs b/WinUIGallery/Samples/ControlPages/EasingFunctionPage.xaml.cs index ae85a0458..bc288f094 100644 --- a/WinUIGallery/Samples/ControlPages/EasingFunctionPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/EasingFunctionPage.xaml.cs @@ -64,10 +64,18 @@ private void Button3_Click(object sender, RoutedEventArgs e) private void Button4_Click(object sender, RoutedEventArgs e) { - var selectedItem = EasingComboBox.SelectedItem as NamedEasingFunction; + if (EasingComboBox.SelectedItem is not NamedEasingFunction selectedItem) + { + return; + } + var easingFunction = selectedItem.EasingFunctionBase; easingFunction.EasingMode = GetEaseValue(); - (Storyboard4.Children[0] as DoubleAnimation).EasingFunction = easingFunction; + + if (Storyboard4.Children[0] is DoubleAnimation doubleAnimation) + { + doubleAnimation.EasingFunction = easingFunction; + } Storyboard4.Children[0].SetValue(DoubleAnimation.FromProperty, Translation4.X); Storyboard4.Children[0].SetValue(DoubleAnimation.ToProperty, Translation4.X > 0 ? 0 : 200); diff --git a/WinUIGallery/Samples/ControlPages/ExpanderPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ExpanderPage.xaml.cs index 98b755b64..0c2843789 100644 --- a/WinUIGallery/Samples/ControlPages/ExpanderPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ExpanderPage.xaml.cs @@ -14,7 +14,7 @@ public ExpanderPage() private void ExpandDirectionComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { - string expandDirection = e.AddedItems[0].ToString(); + string? expandDirection = e.AddedItems[0].ToString(); switch (expandDirection) { diff --git a/WinUIGallery/Samples/ControlPages/Fundamentals/BindingPage.xaml.cs b/WinUIGallery/Samples/ControlPages/Fundamentals/BindingPage.xaml.cs index 98e1dc6b5..9ce72e4df 100644 --- a/WinUIGallery/Samples/ControlPages/Fundamentals/BindingPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/Fundamentals/BindingPage.xaml.cs @@ -21,7 +21,7 @@ public BindingPage() { Title = "Welcome to WinUI 3", Description = "This is an example of binding to a view model.", - NullString = null + NullString = string.Empty, }; DataContext = ViewModel; } @@ -41,9 +41,9 @@ public string FormatDate(DateTimeOffset? date) public partial class ExampleViewModel : INotifyPropertyChanged { - private string _title; - private string _description; - private string _nullString; + private string _title = string.Empty; + private string _description = string.Empty; + private string _nullString = string.Empty; public string Title { @@ -84,7 +84,7 @@ public string NullString } } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; protected void OnPropertyChanged(string propertyName) { diff --git a/WinUIGallery/Samples/ControlPages/Fundamentals/Controls/CounterControl.cs b/WinUIGallery/Samples/ControlPages/Fundamentals/Controls/CounterControl.cs index 335b1d3af..879230aff 100644 --- a/WinUIGallery/Samples/ControlPages/Fundamentals/Controls/CounterControl.cs +++ b/WinUIGallery/Samples/ControlPages/Fundamentals/Controls/CounterControl.cs @@ -39,8 +39,8 @@ public CounterMode Mode set => SetValue(ModeProperty, value); } - private Button ActionButton; - private TextBlock CountText; + private Button? ActionButton; + private TextBlock? CountText; protected override void OnApplyTemplate() { diff --git a/WinUIGallery/Samples/ControlPages/Fundamentals/Controls/ValidatedPasswordBox.cs b/WinUIGallery/Samples/ControlPages/Fundamentals/Controls/ValidatedPasswordBox.cs index 8f073bb33..734f3ae74 100644 --- a/WinUIGallery/Samples/ControlPages/Fundamentals/Controls/ValidatedPasswordBox.cs +++ b/WinUIGallery/Samples/ControlPages/Fundamentals/Controls/ValidatedPasswordBox.cs @@ -39,8 +39,8 @@ public ValidatedPasswordBox() public string Header { get => (string)GetValue(HeaderProperty); set => SetValue(HeaderProperty, value); } public string PlaceholderText { get => (string)GetValue(PlaceholderTextProperty); set => SetValue(PlaceholderTextProperty, value); } - private PasswordBox PasswordInput { get; set; } - private RichTextBlock ValidationRichText { get; set; } + private PasswordBox? PasswordInput { get; set; } + private RichTextBlock? ValidationRichText { get; set; } protected override void OnApplyTemplate() { diff --git a/WinUIGallery/Samples/ControlPages/Fundamentals/ScratchPadPage.xaml.cs b/WinUIGallery/Samples/ControlPages/Fundamentals/ScratchPadPage.xaml.cs index 25bd5d35b..476b21816 100644 --- a/WinUIGallery/Samples/ControlPages/Fundamentals/ScratchPadPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/Fundamentals/ScratchPadPage.xaml.cs @@ -69,16 +69,17 @@ private string GetDefaultScratchXAML() "; } - public string ReadScratchPadXAMLinLocalSettings() + public string? ReadScratchPadXAMLinLocalSettings() { var appData = Microsoft.Windows.Storage.ApplicationData.GetDefault(); if (appData.LocalSettings.Containers.ContainsKey(containerKey)) { var scratchPadContainer = appData.LocalSettings.CreateContainer(containerKey, Microsoft.Windows.Storage.ApplicationDataCreateDisposition.Existing); - if (scratchPadContainer != null && scratchPadContainer.Values.ContainsKey(xamlCompositeValueKey)) + + // String values are limited to 4K characters. Use a composite value to support a longer string. + if (scratchPadContainer?.Values.TryGetValue(xamlCompositeValueKey, out var value) is true && + value is ApplicationDataCompositeValue compositeStr) { - // String values are limited to 4K characters. Use a composite value to support a longer string. - var compositeStr = scratchPadContainer.Values[xamlCompositeValueKey] as ApplicationDataCompositeValue; var xamlStr = ""; int count = (int)compositeStr[xamlSegmentCountKey]; for (int i = 0; i < count; i++) diff --git a/WinUIGallery/Samples/ControlPages/GridViewPage.xaml.cs b/WinUIGallery/Samples/ControlPages/GridViewPage.xaml.cs index 3acd5a96b..6708537e0 100644 --- a/WinUIGallery/Samples/ControlPages/GridViewPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/GridViewPage.xaml.cs @@ -12,7 +12,7 @@ namespace WinUIGallery.ControlPages; public sealed partial class GridViewPage : ItemsPageBase { - ItemsWrapGrid StyledGridIWG; + ItemsWrapGrid? StyledGridIWG; public GridViewPage() { @@ -43,10 +43,10 @@ protected override void OnNavigatedTo(NavigationEventArgs e) private void ItemTemplate_Checked(object sender, RoutedEventArgs e) { - var tag = (sender as FrameworkElement).Tag; + object? tag = (sender as FrameworkElement)?.Tag; if (tag != null) { - string template = tag.ToString(); + string? template = tag.ToString(); ContentGridView.ItemTemplate = (DataTemplate)this.Resources[template]; itemTemplate.Value = template; @@ -127,12 +127,22 @@ private void ContentGridView_SelectionChanged(object sender, SelectionChangedEve private void ContentGridView_ItemClick(object sender, ItemClickEventArgs e) { - ClickOutput.Text = "You clicked " + (e.ClickedItem as CustomDataObject).Title + "."; + if (e.ClickedItem is not CustomDataObject clickedItem) + { + return; + } + + ClickOutput.Text = "You clicked " + clickedItem.Title + "."; } private void BasicGridView_ItemClick(object sender, ItemClickEventArgs e) { - ClickOutput0.Text = "You clicked " + (e.ClickedItem as CustomDataObject).Title + "."; + if (e.ClickedItem is not CustomDataObject clickedItem) + { + return; + } + + ClickOutput0.Text = "You clicked " + clickedItem.Title + "."; } private void ItemClickCheckBox_Click(object sender, RoutedEventArgs e) @@ -156,7 +166,7 @@ private void SelectionModeComboBox_SelectionChanged(object sender, SelectionChan { if (ContentGridView != null) { - string colorName = e.AddedItems[0].ToString(); + string? colorName = e.AddedItems[0].ToString(); switch (colorName) { case "None": @@ -178,8 +188,13 @@ private void SelectionModeComboBox_SelectionChanged(object sender, SelectionChan private void StyledGrid_InitWrapGrid(object sender, RoutedEventArgs e) { + if (sender is not ItemsWrapGrid itemsWrapGrid) + { + return; + } + // Update ItemsWrapGrid object created on page load by assigning it to StyledGrid's ItemWrapGrid - StyledGridIWG = sender as ItemsWrapGrid; + StyledGridIWG = itemsWrapGrid; // Now we can change StyledGrid's MaximumRowsorColumns property within its ItemsPanel>ItemsPanelTemplate>ItemsWrapGrid. StyledGridIWG.MaximumRowsOrColumns = 3; @@ -201,7 +216,10 @@ private void NumberBox_ValueChanged(Microsoft.UI.Xaml.Controls.NumberBox sender, int columnSpace = (int)ColumnSpace.Value; for (int i = 0; i < StyledGrid.Items.Count; i++) { - GridViewItem item = StyledGrid.ContainerFromIndex(i) as GridViewItem; + if (StyledGrid.ContainerFromIndex(i) is not GridViewItem item) + { + continue; + } Thickness NewMargin = item.Margin; NewMargin.Left = columnSpace; diff --git a/WinUIGallery/Samples/ControlPages/IconElementPage.xaml.cs b/WinUIGallery/Samples/ControlPages/IconElementPage.xaml.cs index ecbc6fa46..c1e7032d5 100644 --- a/WinUIGallery/Samples/ControlPages/IconElementPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/IconElementPage.xaml.cs @@ -17,7 +17,7 @@ public IconElementPage() private void MonochromeButton_CheckedChanged(object sender, RoutedEventArgs e) { - SlicesIcon.ShowAsMonochrome = (bool)MonochromeButton.IsChecked; + SlicesIcon.ShowAsMonochrome = MonochromeButton.IsChecked is true; SlicesIcon.UriSource = new Uri("ms-appx:///Assets/SampleMedia/Slices.png"); } } diff --git a/WinUIGallery/Samples/ControlPages/ImagePage.xaml.cs b/WinUIGallery/Samples/ControlPages/ImagePage.xaml.cs index 099df36cd..8aa838f12 100644 --- a/WinUIGallery/Samples/ControlPages/ImagePage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ImagePage.xaml.cs @@ -17,9 +17,9 @@ public ImagePage() private void ImageStretch_Checked(object sender, RoutedEventArgs e) { - if (StretchImage != null) + if ((sender as RadioButton)?.Content.ToString() is string strStretch && + StretchImage != null) { - var strStretch = (sender as RadioButton).Content.ToString(); var stretch = (Stretch)Enum.Parse(typeof(Stretch), strStretch); StretchImage.Stretch = stretch; } diff --git a/WinUIGallery/Samples/ControlPages/ImplicitTransitionPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ImplicitTransitionPage.xaml.cs index 50c9fe72a..75f897340 100644 --- a/WinUIGallery/Samples/ControlPages/ImplicitTransitionPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ImplicitTransitionPage.xaml.cs @@ -32,24 +32,52 @@ void SetupImplicitTransitionsIfAPIAvailable() } private void OpacityButton_Click(object sender, RoutedEventArgs e) + { + float opacity = EnsureValueIsNumber(OpacityNumberBox); + ApplyOpacity(opacity); + } + + private void ApplyOpacity(float opacity) { // If the implicit animation API is not present, simply no-op. if (!(ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 7))) return; - var customValue = EnsureValueIsNumber(OpacityNumberBox); - OpacityRectangle.Opacity = customValue; - OpacityValue.Value = customValue; + + OpacityRectangle.Opacity = opacity; + OpacityValue.Value = opacity; // announce visual change to automation UIHelper.AnnounceActionForAccessibility(OpacityBtn, $"Rectangle opacity changed by {OpacityValue.Value} points", "RectangleChangedNotificationActivityId"); } + private void RotationButton_Click(object sender, RoutedEventArgs e) + { + float rotation = EnsureValueIsNumber(RotationNumberBox); + ApplyRotation(rotation); + } + + private void ApplyRotation(float rotation) { RotationRectangle.CenterPoint = new System.Numerics.Vector3((float)RotationRectangle.ActualWidth / 2, (float)RotationRectangle.ActualHeight / 2, 0f); - RotationRectangle.Rotation = EnsureValueIsNumber(RotationNumberBox); + RotationRectangle.Rotation = rotation; // announce visual change to automation UIHelper.AnnounceActionForAccessibility(RotateBtn, $"Rectangle rotated by {RotationNumberBox.Value} degrees", "RectangleChangedNotificationActivityId"); } + private void ScaleButton_Click(object sender, RoutedEventArgs e) + { + float scale; + if ((sender as Button)?.Tag is { } tag) + { + scale = (float)Convert.ToDouble(tag); + } + else + { + scale = EnsureValueIsNumber(ScaleNumberBox); + } + ApplyScale(scale); + } + + private void ApplyScale(float scale) { var _scaleTransition = ScaleRectangle.ScaleTransition; @@ -57,24 +85,27 @@ private void ScaleButton_Click(object sender, RoutedEventArgs e) ((ScaleY.IsChecked == true) ? Vector3TransitionComponents.Y : 0) | ((ScaleZ.IsChecked == true) ? Vector3TransitionComponents.Z : 0); - float customValue; + ScaleRectangle.Scale = new Vector3(scale); + ScaleValue.Value = scale; + // announce visual change to automation + UIHelper.AnnounceActionForAccessibility(ScaleBtn, $"Rectangle scaled by {ScaleValue.Value} points", "RectangleChangedNotificationActivityId"); + } - if (sender != null && (sender as Button).Tag != null) + private void TranslateButton_Click(object sender, RoutedEventArgs e) + { + float translation; + if ((sender as Button)?.Tag is { } tag) { - customValue = (float)Convert.ToDouble((sender as Button).Tag); + translation = (float)Convert.ToDouble(tag); } else { - customValue = EnsureValueIsNumber(ScaleNumberBox); + translation = EnsureValueIsNumber(TranslationNumberBox); } - - ScaleRectangle.Scale = new Vector3(customValue); - ScaleValue.Value = customValue; - // announce visual change to automation - UIHelper.AnnounceActionForAccessibility(ScaleBtn, $"Rectangle scaled by {ScaleValue.Value} points", "RectangleChangedNotificationActivityId"); + ApplyTranslation(translation); } - private void TranslateButton_Click(object sender, RoutedEventArgs e) + private void ApplyTranslation(float translation) { var _translationTransition = TranslateRectangle.TranslationTransition; @@ -82,41 +113,36 @@ private void TranslateButton_Click(object sender, RoutedEventArgs e) ((TranslateY.IsChecked == true) ? Vector3TransitionComponents.Y : 0) | ((TranslateZ.IsChecked == true) ? Vector3TransitionComponents.Z : 0); - float customValue; - if (sender != null && (sender as Button).Tag != null) - { - customValue = (float)Convert.ToDouble((sender as Button).Tag); - } - else - { - customValue = EnsureValueIsNumber(TranslationNumberBox); - } - - TranslateRectangle.Translation = new Vector3(customValue); - TranslationValue.Value = customValue; + TranslateRectangle.Translation = new Vector3(translation); + TranslationValue.Value = translation; // announce visual change to automation UIHelper.AnnounceActionForAccessibility(TranslateBtn, $"Rectangle translated by {TranslationValue.Value} points", "RectangleChangedNotificationActivityId"); } private void NumberBox_KeyDown(object sender, KeyRoutedEventArgs e) { + if ((sender as NumberBox)?.Header is not string header) + { + return; + } + if (e.Key == Windows.System.VirtualKey.Enter) { - if ((string)(sender as NumberBox).Header == "Opacity (0.0 to 1.0)") + if (header == "Opacity (0.0 to 1.0)") { - OpacityButton_Click(null, null); + ApplyOpacity(EnsureValueIsNumber(OpacityNumberBox)); } - if ((string)(sender as NumberBox).Header == "Rotation (0.0 to 360.0)") + if (header == "Rotation (0.0 to 360.0)") { - RotationButton_Click(null, null); + ApplyRotation(EnsureValueIsNumber(RotationNumberBox)); } - if ((string)(sender as NumberBox).Header == "Scale (0.0 to 5.0)") + if (header == "Scale (0.0 to 5.0)") { - ScaleButton_Click(null, null); + ApplyScale(EnsureValueIsNumber(ScaleNumberBox)); } - if ((string)(sender as NumberBox).Header == "Translation (0.0 to 200.0)") + if (header == "Translation (0.0 to 200.0)") { - TranslateButton_Click(null, null); + ApplyTranslation(EnsureValueIsNumber(TranslationNumberBox)); } } } @@ -124,7 +150,7 @@ private void NumberBox_KeyDown(object sender, KeyRoutedEventArgs e) private void BackgroundButton_Click(object sender, RoutedEventArgs e) { - if ((BrushPresenter.Background as SolidColorBrush).Color == Microsoft.UI.Colors.Blue) + if ((BrushPresenter.Background as SolidColorBrush)?.Color == Microsoft.UI.Colors.Blue) { BrushPresenter.Background = new SolidColorBrush(Microsoft.UI.Colors.Yellow); // announce visual change to automation diff --git a/WinUIGallery/Samples/ControlPages/InfoBadgePage.xaml.cs b/WinUIGallery/Samples/ControlPages/InfoBadgePage.xaml.cs index 71aa48328..6a97ca72f 100644 --- a/WinUIGallery/Samples/ControlPages/InfoBadgePage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/InfoBadgePage.xaml.cs @@ -24,7 +24,7 @@ public double InfoBadgeOpacity public void NavigationViewDisplayMode_SelectionChanged(object sender, SelectionChangedEventArgs e) { - string paneDisplayMode = e.AddedItems[0].ToString(); + string? paneDisplayMode = e.AddedItems[0].ToString(); switch (paneDisplayMode) { @@ -52,7 +52,7 @@ private void ToggleInfoBadgeOpacity_Toggled(object sender, RoutedEventArgs e) public void InfoBadgeStyleComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { - string infoBadgeStyle = e.AddedItems[0].ToString(); + string? infoBadgeStyle = e.AddedItems[0].ToString(); switch (infoBadgeStyle) { diff --git a/WinUIGallery/Samples/ControlPages/InfoBarPage.xaml.cs b/WinUIGallery/Samples/ControlPages/InfoBarPage.xaml.cs index f407e9da1..ad60e9e14 100644 --- a/WinUIGallery/Samples/ControlPages/InfoBarPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/InfoBarPage.xaml.cs @@ -22,7 +22,7 @@ protected override void OnNavigatedTo(NavigationEventArgs e) private void SeverityComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { - string severityName = e.AddedItems[0].ToString(); + string? severityName = e.AddedItems[0].ToString(); switch (severityName) { diff --git a/WinUIGallery/Samples/ControlPages/ItemsRepeaterPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ItemsRepeaterPage.xaml.cs index bafbbfc4d..eca86cc6c 100644 --- a/WinUIGallery/Samples/ControlPages/ItemsRepeaterPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ItemsRepeaterPage.xaml.cs @@ -24,12 +24,12 @@ public sealed partial class ItemsRepeaterPage : ItemsPageBase private int MaxLength = 425; public ObservableCollection Numbers { get; } = new ObservableCollection(Enumerable.Range(0, 500)); - public ObservableCollection BarItems; - public MyItemsSource filteredRecipeData = new MyItemsSource(null); - public List staticRecipeData; + public ObservableCollection? BarItems; + public MyItemsSource filteredRecipeData = new MyItemsSource([]); + public List staticRecipeData = []; private bool IsSortDescending = false; - private Button LastSelectedColorButton; + private Button? LastSelectedColorButton; private int PreviouslyFocusedAnimatedScrollRepeaterIndex = -1; public ItemsRepeaterPage() @@ -146,13 +146,13 @@ private ObservableCollection GetProteins() // ========================================================================== private void AddBtn_Click(object sender, RoutedEventArgs e) { - BarItems.Add(new Bar(random.Next(this.MaxLength), this.MaxLength)); + BarItems?.Add(new Bar(random.Next(this.MaxLength), this.MaxLength)); DeleteBtn.IsEnabled = true; } private void DeleteBtn_Click(object sender, RoutedEventArgs e) { - if (BarItems.Count > 0) + if (BarItems?.Count > 0) { BarItems.RemoveAt(0); if (BarItems.Count == 0) @@ -164,14 +164,13 @@ private void DeleteBtn_Click(object sender, RoutedEventArgs e) private void RadioBtn_Click(object sender, SelectionChangedEventArgs e) { - string itemTemplateKey = string.Empty; - var selected = (sender as Microsoft.UI.Xaml.Controls.RadioButtons).SelectedItem; - if (selected == null) + if (((sender as RadioButtons)?.SelectedItem as FrameworkElement)?.Tag is not string layoutKey) { // No point in continuing if selected element is null return; } - var layoutKey = ((FrameworkElement)selected).Tag as string; + + string itemTemplateKey = string.Empty; if (layoutKey.Equals(nameof(this.VerticalStackLayout))) // we used x:Name in the resources which both acts as the x:Key value and creates a member field by the same name { @@ -232,11 +231,8 @@ private void RadioBtn_Click(object sender, SelectionChangedEventArgs e) // ========================================================================== private void LayoutBtn_SelectionChanged(object sender, SelectionChangedEventArgs e) { - var radioButtons = sender as Microsoft.UI.Xaml.Controls.RadioButtons; - if (radioButtons?.SelectedItem is RadioButton selectedRadioButton) + if (((sender as RadioButtons)?.SelectedItem as RadioButton)?.Tag is string layoutKey) { - string layoutKey = selectedRadioButton.Tag as string; - repeater2.Layout = Resources[layoutKey] as Microsoft.UI.Xaml.Controls.VirtualizingLayout; layout2.Value = layoutKey; @@ -260,7 +256,10 @@ private void LayoutBtn_SelectionChanged(object sender, SelectionChangedEventArgs private void OnAnimatedItemGotFocus(object sender, RoutedEventArgs e) { - var item = sender as FrameworkElement; + if (sender is not FrameworkElement item) + { + return; + } // Store the last focused Index so we can land back on it when focus leaves // and comes back to the repeater. @@ -287,11 +286,15 @@ private void OnAnimatedScrollRepeaterGettingFocus(UIElement sender, GettingFocus private void OnAnimatedItemClicked(object sender, RoutedEventArgs e) { + if (sender is not Button senderBtn) + { + return; + } + // Update corresponding rectangle with selected color - Button senderBtn = sender as Button; colorRectangle.Fill = senderBtn.Background; // announce visual change to automation - UIHelper.AnnounceActionForAccessibility(sender as UIElement, $"Rectangle color set to {(sender as ContentControl).Content}", "RectangleChangedNotificationActivityId"); + UIHelper.AnnounceActionForAccessibility(senderBtn, $"Rectangle color set to {senderBtn.Content}", "RectangleChangedNotificationActivityId"); SetUIANamesForSelectedEntry(senderBtn); } @@ -424,7 +427,7 @@ private void OnAnimatedScrollRepeaterKeyDown(object sender, KeyRoutedEventArgs e { var element = animatedScrollRepeater.GetOrCreateElement(targetIndex); element.StartBringIntoView(); - (element as Control).Focus(FocusState.Programmatic); + (element as Control)?.Focus(FocusState.Programmatic); e.Handled = true; } } @@ -445,10 +448,10 @@ public NestedCategory(string catName, ObservableCollection catItems) public partial class MyDataTemplateSelector : DataTemplateSelector { - public DataTemplate Normal { get; set; } - public DataTemplate Accent { get; set; } + public DataTemplate? Normal { get; set; } + public DataTemplate? Accent { get; set; } - protected override DataTemplate SelectTemplateCore(object item) + protected override DataTemplate? SelectTemplateCore(object item) { if ((int)item % 2 == 0) { @@ -465,11 +468,11 @@ public partial class StringOrIntTemplateSelector : DataTemplateSelector { // Define the (currently empty) data templates to return // These will be "filled-in" in the XAML code. - public DataTemplate StringTemplate { get; set; } + public DataTemplate? StringTemplate { get; set; } - public DataTemplate IntTemplate { get; set; } + public DataTemplate? IntTemplate { get; set; } - protected override DataTemplate SelectTemplateCore(object item) + protected override DataTemplate? SelectTemplateCore(object item) { // Return the correct data template based on the item's type. if (item.GetType() == typeof(string)) @@ -513,10 +516,10 @@ public Bar(double length, int max) public class Recipe { public int Num { get; set; } - public string Ingredients { get; set; } - public List IngList { get; set; } - public string Name { get; set; } - public string Color { get; set; } + public string Ingredients { get; set; } = string.Empty; + public List IngList { get; set; } = []; + public string Name { get; set; } = string.Empty; + public string Color { get; set; } = string.Empty; public int NumIngredients { get @@ -553,7 +556,7 @@ public void RandomizeIngredients() } // Custom data source class that assigns elements unique IDs, making filtering easier -public partial class MyItemsSource : IList, Microsoft.UI.Xaml.Controls.IKeyIndexMapping, INotifyCollectionChanged +public partial class MyItemsSource : IList, IKeyIndexMapping, INotifyCollectionChanged { private List inner = new List(); @@ -576,7 +579,7 @@ public void InitializeCollection(IEnumerable collection) #region IReadOnlyList public int Count => this.inner != null ? this.inner.Count : 0; - public object this[int index] + public object? this[int index] { get { @@ -585,7 +588,12 @@ public object this[int index] set { - inner[index] = (Recipe)value; + if (value is not Recipe recipe) + { + throw new ArgumentException("Value must be of type Recipe.", nameof(value)); + } + + inner[index] = recipe; } } @@ -594,7 +602,7 @@ public object this[int index] #endregion #region INotifyCollectionChanged - public event NotifyCollectionChangedEventHandler CollectionChanged; + public event NotifyCollectionChangedEventHandler? CollectionChanged; #endregion @@ -624,7 +632,7 @@ IEnumerator IEnumerable.GetEnumerator() throw new NotImplementedException(); } - public int Add(object value) + public int Add(object? value) { throw new NotImplementedException(); } @@ -634,22 +642,22 @@ public void Clear() throw new NotImplementedException(); } - public bool Contains(object value) + public bool Contains(object? value) { throw new NotImplementedException(); } - public int IndexOf(object value) + public int IndexOf(object? value) { throw new NotImplementedException(); } - public void Insert(int index, object value) + public void Insert(int index, object? value) { throw new NotImplementedException(); } - public void Remove(object value) + public void Remove(object? value) { throw new NotImplementedException(); } diff --git a/WinUIGallery/Samples/ControlPages/ItemsViewPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ItemsViewPage.xaml.cs index f706cb9c4..8fe7c8fb0 100644 --- a/WinUIGallery/Samples/ControlPages/ItemsViewPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ItemsViewPage.xaml.cs @@ -12,13 +12,13 @@ namespace WinUIGallery.ControlPages; public sealed partial class ItemsViewPage : ItemsPageBase { - private LinedFlowLayout linedFlowLayout = null; - private StackLayout stackLayout = null; - private UniformGridLayout uniformGridLayout = null; + private LinedFlowLayout? linedFlowLayout = null; + private StackLayout? stackLayout = null; + private UniformGridLayout? uniformGridLayout = null; - private DataTemplate linedFlowLayoutItemTemplate = null; - private DataTemplate stackLayoutItemTemplate = null; - private DataTemplate uniformGridLayoutItemTemplate = null; + private DataTemplate? linedFlowLayoutItemTemplate = null; + private DataTemplate? stackLayoutItemTemplate = null; + private DataTemplate? uniformGridLayoutItemTemplate = null; private bool applyLinedFlowLayoutLineHeightAsync = false; private bool applyLinedFlowLayoutOptionsAsync = false; @@ -72,7 +72,12 @@ private void ItemsViewPage_Loaded(object sender, RoutedEventArgs e) // Example1 private void BasicItemsView_ItemInvoked(ItemsView sender, ItemsViewItemInvokedEventArgs e) { - tblBasicInvokeOutput.Text = "You invoked " + (e.InvokedItem as CustomDataObject).Title + "."; + if (e.InvokedItem is not CustomDataObject invokedItem) + { + return; + } + + tblBasicInvokeOutput.Text = "You invoked " + invokedItem.Title + "."; } // Example2 @@ -80,7 +85,7 @@ private void ApplyLinedFlowLayoutLineHeight() { if (linedFlowLayout != null && rbSmallLineHeight != null) { - linedFlowLayout.LineHeight = (bool)rbSmallLineHeight.IsChecked ? 80 : 160; + linedFlowLayout.LineHeight = rbSmallLineHeight.IsChecked is true ? 80 : 160; } } @@ -225,7 +230,12 @@ private void SwappableLayoutsItemsViewScrollView_ViewChanged(ScrollView sender, // Example3 private void SwappableSelectionModesItemsView_ItemInvoked(ItemsView sender, ItemsViewItemInvokedEventArgs e) { - tblInvocationOutput.Text = "You invoked " + (e.InvokedItem as CustomDataObject).Title + "."; + if (e.InvokedItem is not CustomDataObject invokedItem) + { + return; + } + + tblInvocationOutput.Text = "You invoked " + invokedItem.Title + "."; } private void SwappableSelectionModesItemsView_SelectionChanged(ItemsView sender, ItemsViewSelectionChangedEventArgs e) @@ -250,7 +260,7 @@ private void ChkIsItemInvokedEnabled_IsCheckedChanged(object sender, RoutedEvent if (SwappableSelectionModesItemsView != null && chkIsItemInvokedEnabled != null) { - SwappableSelectionModesItemsView.IsItemInvokedEnabled = (bool)chkIsItemInvokedEnabled.IsChecked; + SwappableSelectionModesItemsView.IsItemInvokedEnabled = chkIsItemInvokedEnabled.IsChecked is true; } } } diff --git a/WinUIGallery/Samples/ControlPages/ListBoxPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ListBoxPage.xaml.cs index c30322408..81767f675 100644 --- a/WinUIGallery/Samples/ControlPages/ListBoxPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ListBoxPage.xaml.cs @@ -15,7 +15,7 @@ public ListBoxPage() private void ColorListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { - string colorName = e.AddedItems[0].ToString(); + string? colorName = e.AddedItems[0].ToString(); switch (colorName) { case "Yellow": diff --git a/WinUIGallery/Samples/ControlPages/ListViewPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ListViewPage.xaml.cs index 9d3a7563c..a63b69ba5 100644 --- a/WinUIGallery/Samples/ControlPages/ListViewPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ListViewPage.xaml.cs @@ -8,7 +8,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; -using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel.DataTransfer; using WinUIGallery.Helpers; @@ -24,7 +23,7 @@ public sealed partial class ListViewPage : ItemsPageBase ObservableCollection contacts3Filtered = new ObservableCollection(); ObservableCollection contacts4ContextMenu = new ObservableCollection(); - ItemsStackPanel stackPanelObj; + ItemsStackPanel? stackPanelObj; int messageNumber; @@ -78,7 +77,7 @@ private void SelectionModeComboBox_SelectionChanged(object sender, SelectionChan { if (Control2 != null) { - string selectionMode = e.AddedItems[0].ToString(); + string? selectionMode = e.AddedItems[0].ToString(); switch (selectionMode) { case "None": @@ -209,7 +208,7 @@ private void Target_DragEnter(object sender, DragEventArgs e) //=================================================================================================================== private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e) { - if (StickySwitch != null) + if (StickySwitch != null && stackPanelObj is not null) { if (StickySwitch.IsOn == true) { @@ -313,8 +312,11 @@ private void TextBlock_IsTextTrimmedChanged(TextBlock sender, IsTextTrimmedChang private void ContactDeleteMenuItem_Click(object sender, RoutedEventArgs e) { - var item = (sender as FrameworkElement).DataContext; - var contact = item as Contact; + if ((sender as FrameworkElement)?.DataContext is not Contact contact) + { + return; + } + contacts4ContextMenu.Remove(contact); } } @@ -390,10 +392,10 @@ public partial class GroupInfoList : List public GroupInfoList(IEnumerable items) : base(items) { } - public object Key { get; set; } + public object? Key { get; set; } public override string ToString() { - return "Group " + Key.ToString(); + return "Group " + Key?.ToString(); } } diff --git a/WinUIGallery/Samples/ControlPages/MenuBarPage.xaml.cs b/WinUIGallery/Samples/ControlPages/MenuBarPage.xaml.cs index 5b386f4d8..6804bce21 100644 --- a/WinUIGallery/Samples/ControlPages/MenuBarPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/MenuBarPage.xaml.cs @@ -14,19 +14,24 @@ public MenuBarPage() private void OnElementClicked(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) { - var selectedFlyoutItem = sender as MenuFlyoutItem; + if (sender is not MenuFlyoutItem selectedFlyoutItem) + { + return; + } + string exampleNumber = selectedFlyoutItem.Name.Substring(0, 1); + if (exampleNumber == "o") { - SelectedOptionText.Text = "You clicked: " + (sender as MenuFlyoutItem).Text; + SelectedOptionText.Text = "You clicked: " + selectedFlyoutItem.Text; } else if (exampleNumber == "t") { - SelectedOptionText1.Text = "You clicked: " + (sender as MenuFlyoutItem).Text; + SelectedOptionText1.Text = "You clicked: " + selectedFlyoutItem.Text; } else if (exampleNumber == "z") { - SelectedOptionText2.Text = "You clicked: " + (sender as MenuFlyoutItem).Text; + SelectedOptionText2.Text = "You clicked: " + selectedFlyoutItem.Text; } } } diff --git a/WinUIGallery/Samples/ControlPages/MenuFlyoutPage.xaml.cs b/WinUIGallery/Samples/ControlPages/MenuFlyoutPage.xaml.cs index 359e5a9bc..9e4c42a0a 100644 --- a/WinUIGallery/Samples/ControlPages/MenuFlyoutPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/MenuFlyoutPage.xaml.cs @@ -17,7 +17,7 @@ private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e) { if (sender is MenuFlyoutItem selectedItem) { - string sortOption = selectedItem.Tag.ToString(); + string? sortOption = selectedItem.Tag.ToString(); switch (sortOption) { case "rating": diff --git a/WinUIGallery/Samples/ControlPages/NavigationViewPage.xaml.cs b/WinUIGallery/Samples/ControlPages/NavigationViewPage.xaml.cs index f9be8bc24..1045f79c4 100644 --- a/WinUIGallery/Samples/ControlPages/NavigationViewPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/NavigationViewPage.xaml.cs @@ -75,7 +75,7 @@ private void NavigationView_SelectionChanged(Microsoft.UI.Xaml.Controls.Navigati string selectedItemTag = ((string)selectedItem.Tag); sender.Header = "Sample Page " + selectedItemTag.Substring(selectedItemTag.Length - 1); string pageName = "WinUIGallery.SamplePages." + selectedItemTag; - Type pageType = Type.GetType(pageName); + Type? pageType = Type.GetType(pageName); contentFrame.Navigate(pageType); } } @@ -94,7 +94,7 @@ private void NavigationView_SelectionChanged2(Microsoft.UI.Xaml.Controls.Navigat var selectedItem = (Microsoft.UI.Xaml.Controls.NavigationViewItem)args.SelectedItem; string selectedItemTag = ((string)selectedItem.Tag); string pageName = "WinUIGallery.SamplePages." + selectedItemTag; - Type pageType = Type.GetType(pageName); + Type? pageType = Type.GetType(pageName); contentFrame2.Navigate(pageType); } } @@ -116,7 +116,7 @@ private void NavigationView_SelectionChanged4(Microsoft.UI.Xaml.Controls.Navigat string selectedItemTag = selectedItem.Name; sender.Header = "Sample Page " + selectedItemTag.Substring(selectedItemTag.Length - 1); string pageName = "WinUIGallery.SamplePages." + "SamplePage1"; - Type pageType = Type.GetType(pageName); + Type? pageType = Type.GetType(pageName); contentFrame4.Navigate(pageType); } } @@ -134,7 +134,7 @@ private void NavigationView_SelectionChanged5(Microsoft.UI.Xaml.Controls.Navigat string selectedItemTag = ((string)selectedItem.Tag); sender.Header = "Sample Page " + selectedItemTag.Substring(selectedItemTag.Length - 1); string pageName = "WinUIGallery.SamplePages." + selectedItemTag; - Type pageType = Type.GetType(pageName); + Type? pageType = Type.GetType(pageName); contentFrame5.Navigate(pageType); } } @@ -148,7 +148,7 @@ private void NavigationView_SelectionChanged6(Microsoft.UI.Xaml.Controls.Navigat { var selectedItem = (Microsoft.UI.Xaml.Controls.NavigationViewItem)args.SelectedItem; string pageName = "WinUIGallery.SamplePages." + ((string)selectedItem.Tag); - Type pageType = Type.GetType(pageName); + Type? pageType = Type.GetType(pageName); contentFrame6.Navigate(pageType); } } @@ -163,7 +163,7 @@ private void NavigationView_SelectionChanged7(Microsoft.UI.Xaml.Controls.Navigat { var selectedItem = (Microsoft.UI.Xaml.Controls.NavigationViewItem)args.SelectedItem; string pageName = "WinUIGallery.SamplePages." + ((string)selectedItem.Tag); - Type pageType = Type.GetType(pageName); + Type? pageType = Type.GetType(pageName); contentFrame7.Navigate(pageType, null, args.RecommendedNavigationTransitionInfo); } @@ -188,7 +188,7 @@ private void NavigationView_SelectionChanged8(Microsoft.UI.Xaml.Controls.Navigat string selectedItemTag = ((string)selectedItem.Tag); sender.Header = "Sample Page " + selectedItemTag.Substring(selectedItemTag.Length - 1); string pageName = "WinUIGallery.SamplePages." + selectedItemTag; - Type pageType = Type.GetType(pageName); + Type? pageType = Type.GetType(pageName); contentFrame8.Navigate(pageType); } } @@ -197,24 +197,24 @@ private void NavigationView_SelectionChanged9(Microsoft.UI.Xaml.Controls.Navigat { var selectedItem = (Microsoft.UI.Xaml.Controls.NavigationViewItem)args.SelectedItem; string pageName = "WinUIGallery.SamplePages." + ((string)selectedItem.Tag); - Type pageType = Type.GetType(pageName); + Type? pageType = Type.GetType(pageName); contentFrame9.Navigate(pageType, null, args.RecommendedNavigationTransitionInfo); } private void headerCheck_Click(object sender, RoutedEventArgs e) { - nvSample.AlwaysShowHeader = (sender as CheckBox).IsChecked == true ? true : false; + nvSample.AlwaysShowHeader = (sender as CheckBox)?.IsChecked == true ? true : false; } private void settingsCheck_Click(object sender, RoutedEventArgs e) { - nvSample.IsSettingsVisible = (sender as CheckBox).IsChecked == true ? true : false; + nvSample.IsSettingsVisible = (sender as CheckBox)?.IsChecked == true ? true : false; } private void visibleCheck_Click(object sender, RoutedEventArgs e) { - if ((sender as CheckBox).IsChecked == true) + if ((sender as CheckBox)?.IsChecked == true) { nvSample.IsBackButtonVisible = Microsoft.UI.Xaml.Controls.NavigationViewBackButtonVisible.Visible; } @@ -226,12 +226,12 @@ private void visibleCheck_Click(object sender, RoutedEventArgs e) private void enableCheck_Click(object sender, RoutedEventArgs e) { - nvSample.IsBackEnabled = (sender as CheckBox).IsChecked == true ? true : false; + nvSample.IsBackEnabled = (sender as CheckBox)?.IsChecked == true ? true : false; } private void autoSuggestCheck_Click(object sender, RoutedEventArgs e) { - if ((sender as CheckBox).IsChecked == true) + if ((sender as CheckBox)?.IsChecked == true) { AutoSuggestBox asb = new AutoSuggestBox() { QueryIcon = new SymbolIcon(Symbol.Find) }; asb.SetValue(AutomationProperties.NameProperty, "search"); @@ -253,7 +253,7 @@ private void setASBSubstitutionString() private void panemc_Check_Click(object sender, RoutedEventArgs e) { - if ((sender as CheckBox).IsChecked == true) + if ((sender as CheckBox)?.IsChecked == true) { PaneHyperlink.Visibility = Visibility.Visible; } @@ -265,7 +265,7 @@ private void panemc_Check_Click(object sender, RoutedEventArgs e) private void paneFooterCheck_Click(object sender, RoutedEventArgs e) { - if ((sender as CheckBox).IsChecked == true) + if ((sender as CheckBox)?.IsChecked == true) { FooterStackPanel.Visibility = Visibility.Visible; } @@ -277,20 +277,20 @@ private void paneFooterCheck_Click(object sender, RoutedEventArgs e) private void panePositionLeft_Checked(object sender, RoutedEventArgs e) { - if ((sender as RadioButton).IsChecked == true) + if ((sender as RadioButton)?.IsChecked == true) { - if ((sender as RadioButton).Name == "nvSampleLeft" && nvSample != null) + if ((sender as RadioButton)?.Name == "nvSampleLeft" && nvSample != null) { nvSample.PaneDisplayMode = Microsoft.UI.Xaml.Controls.NavigationViewPaneDisplayMode.Left; nvSample.IsPaneOpen = true; FooterStackPanel.Orientation = Orientation.Vertical; } - else if ((sender as RadioButton).Name == "nvSample8Left" && nvSample8 != null) + else if ((sender as RadioButton)?.Name == "nvSample8Left" && nvSample8 != null) { nvSample8.PaneDisplayMode = Microsoft.UI.Xaml.Controls.NavigationViewPaneDisplayMode.Left; nvSample8.IsPaneOpen = true; } - else if ((sender as RadioButton).Name == "nvSample9Left" && nvSample9 != null) + else if ((sender as RadioButton)?.Name == "nvSample9Left" && nvSample9 != null) { nvSample9.PaneDisplayMode = Microsoft.UI.Xaml.Controls.NavigationViewPaneDisplayMode.Left; nvSample9.IsPaneOpen = true; @@ -301,20 +301,20 @@ private void panePositionLeft_Checked(object sender, RoutedEventArgs e) private void panePositionTop_Checked(object sender, RoutedEventArgs e) { - if ((sender as RadioButton).IsChecked == true) + if ((sender as RadioButton)?.IsChecked == true) { - if ((sender as RadioButton).Name == "nvSampleTop" && nvSample != null) + if ((sender as RadioButton)?.Name == "nvSampleTop" && nvSample != null) { nvSample.PaneDisplayMode = Microsoft.UI.Xaml.Controls.NavigationViewPaneDisplayMode.Top; nvSample.IsPaneOpen = false; FooterStackPanel.Orientation = Orientation.Horizontal; } - else if ((sender as RadioButton).Name == "nvSample8Top" && nvSample8 != null) + else if ((sender as RadioButton)?.Name == "nvSample8Top" && nvSample8 != null) { nvSample8.PaneDisplayMode = Microsoft.UI.Xaml.Controls.NavigationViewPaneDisplayMode.Top; nvSample8.IsPaneOpen = false; } - else if ((sender as RadioButton).Name == "nvSample9Top" && nvSample9 != null) + else if ((sender as RadioButton)?.Name == "nvSample9Top" && nvSample9 != null) { nvSample9.PaneDisplayMode = Microsoft.UI.Xaml.Controls.NavigationViewPaneDisplayMode.Top; nvSample9.IsPaneOpen = false; @@ -324,9 +324,9 @@ private void panePositionTop_Checked(object sender, RoutedEventArgs e) private void panePositionLeftCompact_Checked(object sender, RoutedEventArgs e) { - if ((sender as RadioButton).IsChecked == true) + if ((sender as RadioButton)?.IsChecked == true) { - if ((sender as RadioButton).Name == "nvSample8LeftCompact" && nvSample8 != null) + if ((sender as RadioButton)?.Name == "nvSample8LeftCompact" && nvSample8 != null) { nvSample8.PaneDisplayMode = Microsoft.UI.Xaml.Controls.NavigationViewPaneDisplayMode.LeftCompact; nvSample8.IsPaneOpen = false; @@ -336,7 +336,7 @@ private void panePositionLeftCompact_Checked(object sender, RoutedEventArgs e) private void sffCheck_Click(object sender, RoutedEventArgs e) { - if ((sender as CheckBox).IsChecked == true) + if ((sender as CheckBox)?.IsChecked == true) { nvSample.SelectionFollowsFocus = Microsoft.UI.Xaml.Controls.NavigationViewSelectionFollowsFocus.Enabled; } @@ -348,6 +348,6 @@ private void sffCheck_Click(object sender, RoutedEventArgs e) private void suppressselectionCheck_Checked_Click(object sender, RoutedEventArgs e) { - SamplePage2Item.SelectsOnInvoked = (sender as CheckBox).IsChecked == true ? false : true; + SamplePage2Item.SelectsOnInvoked = (sender as CheckBox)?.IsChecked == true ? false : true; } } diff --git a/WinUIGallery/Samples/ControlPages/PageTransitionPage.xaml.cs b/WinUIGallery/Samples/ControlPages/PageTransitionPage.xaml.cs index dea0a85ef..5b2f63d8a 100644 --- a/WinUIGallery/Samples/ControlPages/PageTransitionPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/PageTransitionPage.xaml.cs @@ -9,7 +9,7 @@ namespace WinUIGallery.ControlPages; public sealed partial class PageTransitionPage : Page { - private NavigationTransitionInfo _transitionInfo = null; + private NavigationTransitionInfo? _transitionInfo = null; public PageTransitionPage() { @@ -47,7 +47,7 @@ private void TransitionRadioButton_Checked(object sender, RoutedEventArgs e) { var pageTransitionString = ""; - var senderTransitionString = (sender as RadioButton).Content.ToString(); + var senderTransitionString = (sender as RadioButton)?.Content.ToString(); if (senderTransitionString != "Default") { pageTransitionString = ", new " + senderTransitionString + "NavigationTransitionInfo()"; diff --git a/WinUIGallery/Samples/ControlPages/PipsPagerPage.xaml.cs b/WinUIGallery/Samples/ControlPages/PipsPagerPage.xaml.cs index dec9eb10b..11af5e76e 100644 --- a/WinUIGallery/Samples/ControlPages/PipsPagerPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/PipsPagerPage.xaml.cs @@ -26,7 +26,7 @@ public PipsPagerPage() private void OrientationComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { - string orientation = e.AddedItems[0].ToString(); + string? orientation = e.AddedItems[0].ToString(); switch (orientation) { @@ -43,7 +43,7 @@ private void OrientationComboBox_SelectionChanged(object sender, SelectionChange private void PrevButtonComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { - string prevButtonVisibility = e.AddedItems[0].ToString(); + string? prevButtonVisibility = e.AddedItems[0].ToString(); switch (prevButtonVisibility) { @@ -64,7 +64,7 @@ private void PrevButtonComboBox_SelectionChanged(object sender, SelectionChanged private void NextButtonComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { - string nextButtonVisibility = e.AddedItems[0].ToString(); + string? nextButtonVisibility = e.AddedItems[0].ToString(); switch (nextButtonVisibility) { diff --git a/WinUIGallery/Samples/ControlPages/ProgressRingPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ProgressRingPage.xaml.cs index 1cbcb679a..092637258 100644 --- a/WinUIGallery/Samples/ControlPages/ProgressRingPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ProgressRingPage.xaml.cs @@ -31,7 +31,7 @@ private void Background_SelectionChanged(object sender, SelectionChangedEventArg { var progressRing = (ComboBox)sender == BackgroundComboBox1 ? ProgressRing1 : ProgressRing2; var revealBackgroundProperty = (ComboBox)sender == BackgroundComboBox1 ? RevealBackgroundProperty1 : RevealBackgroundProperty2; - string colorName = e.AddedItems[0].ToString(); + string? colorName = e.AddedItems[0].ToString(); bool showBackgroundProperty = false; switch (colorName) { diff --git a/WinUIGallery/Samples/ControlPages/PullToRefreshPage.xaml.cs b/WinUIGallery/Samples/ControlPages/PullToRefreshPage.xaml.cs index 600fd2e9e..e2d7f9f59 100644 --- a/WinUIGallery/Samples/ControlPages/PullToRefreshPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/PullToRefreshPage.xaml.cs @@ -24,19 +24,19 @@ public sealed partial class PullToRefreshPage : Page private ObservableCollection items2 = new ObservableCollection(); private DispatcherTimer timer1 = new DispatcherTimer(); private DispatcherTimer timer2 = new DispatcherTimer(); - private Visual visualizerContentVisual; - private static RefreshContainer rc2; - private RefreshVisualizer rv2; + private Visual? visualizerContentVisual; + private static RefreshContainer? rc2; + private RefreshVisualizer? rv2; private int items1AddedCount = 0; private int items2AddedCount = 0; - private Deferral RefreshCompletionDeferral1 + private Deferral? RefreshCompletionDeferral1 { get; set; } - private Deferral RefreshCompletionDeferral2 + private Deferral? RefreshCompletionDeferral2 { get; set; @@ -118,11 +118,16 @@ public PullToRefreshPage() private void PullToRefreshPage_Loaded(object sender, RoutedEventArgs e) { + if (rv2 is null) + { + return; + } + visualizerContentVisual = ElementCompositionPreview.GetElementVisual(rv2.Content); this.Loaded -= PullToRefreshPage_Loaded; } - private void Timer1_Tick(object sender, object e) + private void Timer1_Tick(object? sender, object e) { DispatcherQueue disp = rc.DispatcherQueue; if (disp.HasThreadAccess) @@ -138,8 +143,13 @@ private void Timer1_Tick(object sender, object e) } } - private void Timer2_Tick(object sender, object e) + private void Timer2_Tick(object? sender, object e) { + if (rc2 is null) + { + return; + } + DispatcherQueue disp = rc2.DispatcherQueue; if (disp.HasThreadAccess) { @@ -200,6 +210,6 @@ private void rc2_RefreshRequested(RefreshContainer sender, RefreshRequestedEvent private void rv2_RefreshStateChanged(RefreshVisualizer sender, RefreshStateChangedEventArgs args) { - visualizerContentVisual.StopAnimation("RotationAngle"); + visualizerContentVisual?.StopAnimation("RotationAngle"); } } diff --git a/WinUIGallery/Samples/ControlPages/RadialGradientBrushPage.xaml.cs b/WinUIGallery/Samples/ControlPages/RadialGradientBrushPage.xaml.cs index 3cd82c7d6..60b7d1f12 100644 --- a/WinUIGallery/Samples/ControlPages/RadialGradientBrushPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/RadialGradientBrushPage.xaml.cs @@ -26,12 +26,22 @@ private void OnPageLoaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) private void OnSpreadMethodChanged(object sender, SelectionChangedEventArgs e) { - RadialGradientBrushExample.SpreadMethod = Enum.Parse(SpreadMethodComboBox.SelectedValue.ToString()); + if (SpreadMethodComboBox.SelectedValue.ToString() is not string methodString) + { + return; + } + + RadialGradientBrushExample.SpreadMethod = Enum.Parse(methodString); } private void OnMappingModeChanged(object sender, SelectionChangedEventArgs e) { - RadialGradientBrushExample.MappingMode = Enum.Parse(MappingModeComboBox.SelectedValue.ToString()); + if (MappingModeComboBox.SelectedValue.ToString() is not string modeString) + { + return; + } + + RadialGradientBrushExample.MappingMode = Enum.Parse(modeString); InitializeSliders(); } diff --git a/WinUIGallery/Samples/ControlPages/RadioButtonPage.xaml.cs b/WinUIGallery/Samples/ControlPages/RadioButtonPage.xaml.cs index 1e2c6270e..41b02e30a 100644 --- a/WinUIGallery/Samples/ControlPages/RadioButtonPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/RadioButtonPage.xaml.cs @@ -15,6 +15,6 @@ public RadioButtonPage() private void RadioButton_Checked(object sender, RoutedEventArgs e) { - Control1Output.Text = string.Format("You selected {0}", (sender as RadioButton).Content.ToString()); + Control1Output.Text = string.Format("You selected {0}", (sender as RadioButton)?.Content.ToString()); } } diff --git a/WinUIGallery/Samples/ControlPages/RadioButtonsPage.xaml.cs b/WinUIGallery/Samples/ControlPages/RadioButtonsPage.xaml.cs index a339daf7f..67f20e1a7 100644 --- a/WinUIGallery/Samples/ControlPages/RadioButtonsPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/RadioButtonsPage.xaml.cs @@ -18,7 +18,7 @@ private void BackgroundColor_SelectionChanged(object sender, SelectionChangedEve { if (ControlOutput != null && sender is RadioButtons rb) { - string colorName = rb.SelectedItem as string; + string? colorName = rb.SelectedItem as string; switch (colorName) { case "Yellow": @@ -38,7 +38,7 @@ private void BorderBrush_SelectionChanged(object sender, SelectionChangedEventAr { if (ControlOutput != null && sender is RadioButtons rb) { - string colorName = rb.SelectedItem as string; + string? colorName = rb.SelectedItem as string; switch (colorName) { case "Yellow": diff --git a/WinUIGallery/Samples/ControlPages/RichEditBoxPage.xaml.cs b/WinUIGallery/Samples/ControlPages/RichEditBoxPage.xaml.cs index af9edddde..24a46e317 100644 --- a/WinUIGallery/Samples/ControlPages/RichEditBoxPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/RichEditBoxPage.xaml.cs @@ -30,9 +30,9 @@ public RichEditBoxPage() mathEditor2.TextDocument.SetMathMode(RichEditMathMode.MathOnly); } - private void Menu_Opening(object sender, object e) + private void Menu_Opening(object? sender, object e) { - CommandBarFlyout myFlyout = sender as CommandBarFlyout; + CommandBarFlyout? myFlyout = sender as CommandBarFlyout; if (myFlyout != null && myFlyout.Target == REBCustom) { AppBarButton myButton = new AppBarButton @@ -43,7 +43,7 @@ private void Menu_Opening(object sender, object e) } else { - CommandBarFlyout muxFlyout = sender as CommandBarFlyout; + CommandBarFlyout? muxFlyout = sender as CommandBarFlyout; if (muxFlyout != null && muxFlyout.Target == REBCustom) { AppBarButton myButton = new AppBarButton @@ -175,10 +175,13 @@ private void FindBoxHighlightMatches() private void FindBoxRemoveHighlights() { - ITextRange documentRange = editor.Document.GetRange(0, TextConstants.MaxUnitCount); - SolidColorBrush defaultBackground = editor.Background as SolidColorBrush; - SolidColorBrush defaultForeground = editor.Foreground as SolidColorBrush; + if (editor.Background is not SolidColorBrush defaultBackground || + editor.Foreground is not SolidColorBrush defaultForeground) + { + return; + } + ITextRange documentRange = editor.Document.GetRange(0, TextConstants.MaxUnitCount); documentRange.CharacterFormat.BackgroundColor = defaultBackground.Color; documentRange.CharacterFormat.ForegroundColor = defaultForeground.Color; } diff --git a/WinUIGallery/Samples/ControlPages/RichTextBlockPage.xaml.cs b/WinUIGallery/Samples/ControlPages/RichTextBlockPage.xaml.cs index f8f4b2a7e..cb08dec1d 100644 --- a/WinUIGallery/Samples/ControlPages/RichTextBlockPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/RichTextBlockPage.xaml.cs @@ -19,9 +19,9 @@ public RichTextBlockPage() private void HighlightColorCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e) { // Get color to use - var selectedItem = (sender as ComboBox).SelectedItem as ComboBoxItem; + var selectedItem = (sender as ComboBox)?.SelectedItem as ComboBoxItem; var color = Colors.Yellow; - switch (selectedItem.Content as string) + switch (selectedItem?.Content as string) { case "Yellow": color = Colors.Yellow; diff --git a/WinUIGallery/Samples/ControlPages/ScrollViewPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ScrollViewPage.xaml.cs index f5b8a6c3b..aa204c185 100644 --- a/WinUIGallery/Samples/ControlPages/ScrollViewPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ScrollViewPage.xaml.cs @@ -181,7 +181,7 @@ private void BtnScrollWithAnimation_Click(object sender, RoutedEventArgs e) private void ScrollView_ScrollAnimationStarting(ScrollView sender, ScrollingScrollAnimationStartingEventArgs e) { - Vector3KeyFrameAnimation stockKeyFrameAnimation = e.Animation as Vector3KeyFrameAnimation; + Vector3KeyFrameAnimation? stockKeyFrameAnimation = e.Animation as Vector3KeyFrameAnimation; if (stockKeyFrameAnimation != null) { @@ -269,7 +269,7 @@ private void nbAnimationDuration_ValueChanged(NumberBox sender, NumberBoxValueCh private void UpdateExample3Content() { - string sampleCodeFileName = null; + string? sampleCodeFileName = null; switch (cmbVerticalAnimation.SelectedIndex) { @@ -315,6 +315,6 @@ private string GetExample3CodeContent(string sampleCodeFileName) _example3CodeCache[sampleCodeFileName] = content; // Cache the content } } - return content; + return content ?? string.Empty; } } diff --git a/WinUIGallery/Samples/ControlPages/SemanticZoomPage.xaml.cs b/WinUIGallery/Samples/ControlPages/SemanticZoomPage.xaml.cs index f0e189216..51cd5dfe1 100644 --- a/WinUIGallery/Samples/ControlPages/SemanticZoomPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/SemanticZoomPage.xaml.cs @@ -12,13 +12,14 @@ namespace WinUIGallery.ControlPages; public sealed partial class SemanticZoomPage : Page { - private IEnumerable _groups; + private IEnumerable? _groups; public SemanticZoomPage() { this.InitializeComponent(); } - public IEnumerable Groups + + public IEnumerable? Groups { get { return this._groups; } } diff --git a/WinUIGallery/Samples/ControlPages/SoundPage.xaml.cs b/WinUIGallery/Samples/ControlPages/SoundPage.xaml.cs index 1eb6e79ee..ed6a139c8 100644 --- a/WinUIGallery/Samples/ControlPages/SoundPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/SoundPage.xaml.cs @@ -20,7 +20,12 @@ public SoundPage() private void Button_Click(object sender, RoutedEventArgs e) { - var tagInt = int.Parse((string)(sender as Button).Tag); + if ((sender as Button)?.Tag is not string tag) + { + return; + } + + var tagInt = int.Parse(tag); ElementSoundPlayer.Play((ElementSoundKind)tagInt); } diff --git a/WinUIGallery/Samples/ControlPages/SplitViewPage.xaml.cs b/WinUIGallery/Samples/ControlPages/SplitViewPage.xaml.cs index 5dd0c42ba..919101bde 100644 --- a/WinUIGallery/Samples/ControlPages/SplitViewPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/SplitViewPage.xaml.cs @@ -37,13 +37,17 @@ private void SplitViewPage_Loaded(object sender, RoutedEventArgs e) private void NavLinksList_ItemClick(object sender, ItemClickEventArgs e) { - content.Text = (e.ClickedItem as NavLink).Label + " Page"; + if (e.ClickedItem is not NavLink navLink) + { + return; + } + + content.Text = navLink.Label + " Page"; } private void PanePlacement_Toggled(object sender, RoutedEventArgs e) { - var ts = sender as ToggleSwitch; - if (ts.IsOn) + if ((sender as ToggleSwitch)?.IsOn is true) { splitView.PanePlacement = SplitViewPanePlacement.Right; } @@ -74,12 +78,20 @@ private void togglePaneButton_CheckedChanged(object sender, RoutedEventArgs e) private void displayModeCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e) { - splitView.DisplayMode = (SplitViewDisplayMode)Enum.Parse(typeof(SplitViewDisplayMode), (e.AddedItems[0] as ComboBoxItem).Content.ToString()); + if ((e.AddedItems[0] as ComboBoxItem)?.Content.ToString() is not string displayMode) + { + return; + } + + splitView.DisplayMode = (SplitViewDisplayMode)Enum.Parse(typeof(SplitViewDisplayMode), displayMode); } private void paneBackgroundCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e) { - var colorString = (e.AddedItems[0] as ComboBoxItem).Content.ToString(); + if ((e.AddedItems[0] as ComboBoxItem)?.Content.ToString() is not string colorString) + { + return; + } VisualStateManager.GoToState(this, colorString, false); } @@ -87,6 +99,6 @@ private void paneBackgroundCombobox_SelectionChanged(object sender, SelectionCha public class NavLink { - public string Label { get; set; } + public string Label { get; set; } = string.Empty; public Symbol Symbol { get; set; } } diff --git a/WinUIGallery/Samples/ControlPages/StandardUICommandPage.xaml.cs b/WinUIGallery/Samples/ControlPages/StandardUICommandPage.xaml.cs index 445820eb7..01ac8cbb2 100644 --- a/WinUIGallery/Samples/ControlPages/StandardUICommandPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/StandardUICommandPage.xaml.cs @@ -12,8 +12,8 @@ namespace WinUIGallery.ControlPages; public class ListItemData { - public string Text { get; set; } - public ICommand Command { get; set; } + public string Text { get; set; } = string.Empty; + public ICommand? Command { get; set; } public override string ToString() { @@ -96,10 +96,13 @@ private void ListViewRight_ContainerContentChanging(ListViewBase sender, Contain MenuFlyout flyout = new MenuFlyout(); ListItemData data = (ListItemData)args.Item; MenuFlyoutItem item = new MenuFlyoutItem() { Command = data.Command }; - flyout.Opened += delegate (object element, object e) + flyout.Opened += delegate (object? element, object e) { - MenuFlyout flyoutElement = element as MenuFlyout; - ListViewItem elementToHighlight = flyoutElement.Target as ListViewItem; + if ((element as MenuFlyout)?.Target is not ListViewItem elementToHighlight) + { + return; + } + elementToHighlight.IsSelected = true; }; flyout.Items.Add(item); diff --git a/WinUIGallery/Samples/ControlPages/StoragePickersPage.xaml.cs b/WinUIGallery/Samples/ControlPages/StoragePickersPage.xaml.cs index 773c9f0ff..85fb9ec6f 100644 --- a/WinUIGallery/Samples/ControlPages/StoragePickersPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/StoragePickersPage.xaml.cs @@ -61,7 +61,7 @@ private async void PickSingleFileButton_Click(object sender, RoutedEventArgs e) //re-enable the button button.IsEnabled = true; - UIHelper.AnnounceActionForAccessibility(sender as Button, PickedSingleFileTextBlock.Text, "FilePickedNotificationId"); + UIHelper.AnnounceActionForAccessibility(button, PickedSingleFileTextBlock.Text, "FilePickedNotificationId"); } } @@ -218,7 +218,7 @@ private async void PickFolderButton_Click(object sender, RoutedEventArgs e) // re-enable the button button.IsEnabled = true; - UIHelper.AnnounceActionForAccessibility(sender as Button, PickedFolderTextBlock.Text, "FolderPickedNotificationId"); + UIHelper.AnnounceActionForAccessibility(button, PickedFolderTextBlock.Text, "FolderPickedNotificationId"); } } @@ -241,7 +241,7 @@ private async void SelectSuggestedFolderButton_Click(object sender, RoutedEventA button.IsEnabled = true; UIHelper.AnnounceActionForAccessibility( - sender as Button, + button, folder != null && !string.IsNullOrEmpty(folder.Path) ? "Folder selected: " + SuggestedFolderTextBox.Text : "No folder selected", diff --git a/WinUIGallery/Samples/ControlPages/TabViewPage.xaml.cs b/WinUIGallery/Samples/ControlPages/TabViewPage.xaml.cs index 6451992d6..a4c7b7ed5 100644 --- a/WinUIGallery/Samples/ControlPages/TabViewPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/TabViewPage.xaml.cs @@ -12,14 +12,14 @@ namespace WinUIGallery.ControlPages; public class MyData { - public string DataHeader { get; set; } - public Microsoft.UI.Xaml.Controls.IconSource DataIconSource { get; set; } - public object DataContent { get; set; } + public string DataHeader { get; set; } = string.Empty; + public required IconSource DataIconSource { get; set; } + public required object DataContent { get; set; } } public sealed partial class TabViewPage : Page { - ObservableCollection myDatas; + ObservableCollection? myDatas; public TabViewPage() { @@ -37,7 +37,7 @@ private void TabView_Loaded(object sender, RoutedEventArgs e) { for (int i = 0; i < 3; i++) { - (sender as TabView).TabItems.Add(CreateNewTab(i)); + (sender as TabView)?.TabItems.Add(CreateNewTab(i)); } } @@ -102,12 +102,6 @@ private void InitializeDataBindingSampleData() private MyData CreateNewMyData(int index) { - var newData = new MyData - { - DataHeader = $"MyData Doc {index}", - DataIconSource = new Microsoft.UI.Xaml.Controls.SymbolIconSource() { Symbol = Symbol.Placeholder } - }; - Frame frame = new Frame(); switch (index % 3) @@ -123,7 +117,12 @@ private MyData CreateNewMyData(int index) break; } - newData.DataContent = frame; + var newData = new MyData + { + DataHeader = $"MyData Doc {index}", + DataIconSource = new Microsoft.UI.Xaml.Controls.SymbolIconSource() { Symbol = Symbol.Placeholder }, + DataContent = frame, + }; return newData; } @@ -131,13 +130,18 @@ private MyData CreateNewMyData(int index) private void TabViewItemsSourceSample_AddTabButtonClick(TabView sender, object args) { // Add a new MyData item to the collection. TabView automatically generates a TabViewItem. - myDatas.Add(CreateNewMyData(myDatas.Count)); + myDatas?.Add(CreateNewMyData(myDatas.Count)); } private void TabViewItemsSourceSample_TabCloseRequested(TabView sender, TabViewTabCloseRequestedEventArgs args) { + if (args.Item is not MyData myData) + { + return; + } + // Remove the requested MyData object from the collection. - myDatas.Remove(args.Item as MyData); + myDatas?.Remove(myData); } #endregion @@ -145,19 +149,22 @@ private void TabViewItemsSourceSample_TabCloseRequested(TabView sender, TabViewT private void NewTabKeyboardAccelerator_Invoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args) { var senderTabView = args.Element as TabView; - senderTabView.TabItems.Add(CreateNewTab(senderTabView.TabItems.Count)); + senderTabView?.TabItems.Add(CreateNewTab(senderTabView.TabItems.Count)); args.Handled = true; } private void CloseSelectedTabKeyboardAccelerator_Invoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args) { - var InvokedTabView = (args.Element as TabView); + if (args.Element is not TabView invokedTabView) + { + return; + } // Only close the selected tab if it is closeable - if (((TabViewItem)InvokedTabView.SelectedItem).IsClosable) + if ((invokedTabView.SelectedItem as TabViewItem)?.IsClosable is true) { - InvokedTabView.TabItems.Remove(InvokedTabView.SelectedItem); + invokedTabView.TabItems.Remove(invokedTabView.SelectedItem); } args.Handled = true; @@ -165,7 +172,10 @@ private void CloseSelectedTabKeyboardAccelerator_Invoked(KeyboardAccelerator sen private void NavigateToNumberedTabKeyboardAccelerator_Invoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args) { - var InvokedTabView = (args.Element as TabView); + if (args.Element is not TabView invokedTabView) + { + return; + } int tabToSelect = 0; @@ -197,14 +207,14 @@ private void NavigateToNumberedTabKeyboardAccelerator_Invoked(KeyboardAccelerato break; case Windows.System.VirtualKey.Number9: // Select the last tab - tabToSelect = InvokedTabView.TabItems.Count - 1; + tabToSelect = invokedTabView.TabItems.Count - 1; break; } // Only select the tab if it is in the list - if (tabToSelect < InvokedTabView.TabItems.Count) + if (tabToSelect < invokedTabView.TabItems.Count) { - InvokedTabView.SelectedIndex = tabToSelect; + invokedTabView.SelectedIndex = tabToSelect; } args.Handled = true; @@ -213,7 +223,7 @@ private void NavigateToNumberedTabKeyboardAccelerator_Invoked(KeyboardAccelerato private void TabWidthBehaviorComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { - string widthModeString = (e.AddedItems[0] as ComboBoxItem).Content.ToString(); + string? widthModeString = (e.AddedItems[0] as ComboBoxItem)?.Content.ToString(); TabViewWidthMode widthMode = TabViewWidthMode.Equal; switch (widthModeString) { @@ -232,7 +242,7 @@ private void TabWidthBehaviorComboBox_SelectionChanged(object sender, SelectionC private void TabCloseButtonOverlayModeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { - string overlayModeString = (e.AddedItems[0] as ComboBoxItem).Content.ToString(); + string? overlayModeString = (e.AddedItems[0] as ComboBoxItem)?.Content.ToString(); TabViewCloseButtonOverlayMode overlayMode = TabViewCloseButtonOverlayMode.Auto; switch (overlayModeString) { diff --git a/WinUIGallery/Samples/ControlPages/ThemeTransitionPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ThemeTransitionPage.xaml.cs index b61cb92eb..ed9101881 100644 --- a/WinUIGallery/Samples/ControlPages/ThemeTransitionPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ThemeTransitionPage.xaml.cs @@ -73,7 +73,7 @@ private void RepositionButton_Click(object sender, RoutedEventArgs e) private void EntranceAddButton_Click(object sender, RoutedEventArgs e) { - var value = Convert.ToInt32((sender as Button).Tag); + var value = Convert.ToInt32((sender as Button)?.Tag); for (int i = 0; i < value; i++) { diff --git a/WinUIGallery/Samples/ControlPages/ToggleButtonPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ToggleButtonPage.xaml.cs index 9af439ff7..3ab724535 100644 --- a/WinUIGallery/Samples/ControlPages/ToggleButtonPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ToggleButtonPage.xaml.cs @@ -13,7 +13,7 @@ public ToggleButtonPage() this.InitializeComponent(); // Set initial output value. - Control1Output.Text = (bool)Toggle1.IsChecked ? "On" : "Off"; + Control1Output.Text = Toggle1.IsChecked is true ? "On" : "Off"; } private void ToggleButton_Checked(object sender, RoutedEventArgs e) diff --git a/WinUIGallery/Samples/ControlPages/TreeViewPage.xaml.cs b/WinUIGallery/Samples/ControlPages/TreeViewPage.xaml.cs index a259a9a65..11feac62e 100644 --- a/WinUIGallery/Samples/ControlPages/TreeViewPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/TreeViewPage.xaml.cs @@ -78,17 +78,17 @@ public enum ExplorerItemType File, } - public string Name { get; set; } + public string Name { get; set; } = string.Empty; public ExplorerItemType Type { get; set; } public ObservableCollection Children { get; set; } = new ObservableCollection(); } partial class ExplorerItemTemplateSelector : DataTemplateSelector { - public DataTemplate FolderTemplate { get; set; } - public DataTemplate FileTemplate { get; set; } + public DataTemplate? FolderTemplate { get; set; } + public DataTemplate? FileTemplate { get; set; } - protected override DataTemplate SelectTemplateCore(object item) + protected override DataTemplate? SelectTemplateCore(object item) { var explorerItem = (ExplorerItem)item; return explorerItem.Type == ExplorerItem.ExplorerItemType.Folder ? FolderTemplate : FileTemplate; diff --git a/WinUIGallery/Samples/ControlPages/ViewboxPage.xaml.cs b/WinUIGallery/Samples/ControlPages/ViewboxPage.xaml.cs index b78daee1a..8c6dd6aed 100644 --- a/WinUIGallery/Samples/ControlPages/ViewboxPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/ViewboxPage.xaml.cs @@ -19,7 +19,7 @@ private void StretchDirectionButton_Checked(object sender, RoutedEventArgs e) { if (sender is RadioButton rb && Control1 != null) { - string direction = rb.Tag.ToString(); + string? direction = rb.Tag.ToString(); switch (direction) { case "UpOnly": @@ -41,7 +41,7 @@ private void StretchButton_Checked(object sender, RoutedEventArgs e) { if (sender is RadioButton rb && Control1 != null) { - string stretch = rb.Tag.ToString(); + string? stretch = rb.Tag.ToString(); switch (stretch) { case "None": diff --git a/WinUIGallery/Samples/ControlPages/XamlCompInteropPage.xaml.cs b/WinUIGallery/Samples/ControlPages/XamlCompInteropPage.xaml.cs index 18fd27ba1..e737fd44d 100644 --- a/WinUIGallery/Samples/ControlPages/XamlCompInteropPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/XamlCompInteropPage.xaml.cs @@ -21,7 +21,7 @@ public XamlCompInteropPage() } Compositor _compositor = Microsoft.UI.Xaml.Media.CompositionTarget.GetCompositorForCurrentThread(); - private SpringVector3NaturalMotionAnimation _springAnimation; + private SpringVector3NaturalMotionAnimation? _springAnimation; private void NaturalMotionExample_Loaded(object sender, RoutedEventArgs e) { @@ -47,7 +47,7 @@ float GetDampingRatio() { // We need to specify the InvariantCulture since the decimal point depends on the // system language and might parse "0.8" to 8 since the decimal point is a different character - return (float)Convert.ToDouble((DampingStackPanel.SelectedItem as RadioButton).Content, CultureInfo.InvariantCulture); + return (float)Convert.ToDouble((DampingStackPanel.SelectedItem as RadioButton)?.Content, CultureInfo.InvariantCulture); } return 0.6f; } @@ -64,16 +64,26 @@ private void StartAnimationIfAPIPresent(UIElement sender, Microsoft.UI.Compositi private void element_PointerEntered(object sender, PointerRoutedEventArgs e) { + if (sender is not UIElement uiElement || _springAnimation is null) + { + return; + } + UpdateSpringAnimation(1.5f); - StartAnimationIfAPIPresent((sender as UIElement), _springAnimation); + StartAnimationIfAPIPresent(uiElement, _springAnimation); } private void element_PointerExited(object sender, PointerRoutedEventArgs e) { + if (sender is not UIElement uiElement || _springAnimation is null) + { + return; + } + UpdateSpringAnimation(1f); - StartAnimationIfAPIPresent((sender as UIElement), _springAnimation); + StartAnimationIfAPIPresent(uiElement, _springAnimation); } diff --git a/WinUIGallery/Samples/SampleCode/Binding/BindingSample5_csharp.txt b/WinUIGallery/Samples/SampleCode/Binding/BindingSample5_csharp.txt index 9f6ab87df..b5df4bda7 100644 --- a/WinUIGallery/Samples/SampleCode/Binding/BindingSample5_csharp.txt +++ b/WinUIGallery/Samples/SampleCode/Binding/BindingSample5_csharp.txt @@ -30,10 +30,10 @@ namespace YourNamespace public class ExampleViewModel : INotifyPropertyChanged { // Backing field for Title property. - private string _title; + private string _title = string.Empty; // Backing field for Description property. - private string _description; + private string _description = string.Empty; // Property for Title with change notification. public string Title @@ -64,7 +64,7 @@ namespace YourNamespace } // Event to notify subscribers (UI elements) of property changes. - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; // Method to raise the PropertyChanged event. // This notifies the UI to update the bound control. diff --git a/WinUIGallery/Samples/SampleCode/CustomUserControls/CustomUserControlsSample1_cs.txt b/WinUIGallery/Samples/SampleCode/CustomUserControls/CustomUserControlsSample1_cs.txt index 3a11ddfb1..48e798a73 100644 --- a/WinUIGallery/Samples/SampleCode/CustomUserControls/CustomUserControlsSample1_cs.txt +++ b/WinUIGallery/Samples/SampleCode/CustomUserControls/CustomUserControlsSample1_cs.txt @@ -42,8 +42,8 @@ public sealed class CounterControl : Control } // Fields for UI elements retrieved from the control template - private Button ActionButton; - private TextBlock CountText; + private Button? ActionButton; + private TextBlock? CountText; // Method executed when the control's template is applied protected override void OnApplyTemplate() diff --git a/WinUIGallery/Samples/SampleCode/CustomUserControls/CustomUserControlsSample2_cs.txt b/WinUIGallery/Samples/SampleCode/CustomUserControls/CustomUserControlsSample2_cs.txt index 20ec03204..a1c06f2f9 100644 --- a/WinUIGallery/Samples/SampleCode/CustomUserControls/CustomUserControlsSample2_cs.txt +++ b/WinUIGallery/Samples/SampleCode/CustomUserControls/CustomUserControlsSample2_cs.txt @@ -42,8 +42,8 @@ public sealed partial class ValidatedPasswordBox : Control public string PlaceholderText { get => (string)GetValue(PlaceholderTextProperty); set => SetValue(PlaceholderTextProperty, value); } // Template parts for password input and validation messages - private PasswordBox PasswordInput { get; set; } - private RichTextBlock ValidationRichText { get; set; } + private PasswordBox? PasswordInput { get; set; } + private RichTextBlock? ValidationRichText { get; set; } protected override void OnApplyTemplate() { diff --git a/WinUIGallery/Samples/SampleCode/GridView/GridViewSample1_cs.txt b/WinUIGallery/Samples/SampleCode/GridView/GridViewSample1_cs.txt index d34b847f0..99a648b63 100644 --- a/WinUIGallery/Samples/SampleCode/GridView/GridViewSample1_cs.txt +++ b/WinUIGallery/Samples/SampleCode/GridView/GridViewSample1_cs.txt @@ -3,11 +3,11 @@ // CustomDataObject class definition: public class CustomDataObject { - public string Title { get; set; } - public string ImageLocation { get; set; } - public string Views { get; set; } - public string Likes { get; set; } - public string Description { get; set; } + public string Title { get; set; } = string.Empty; + public string ImageLocation { get; set; } = string.Empty; + public string Views { get; set; } = string.Empty; + public string Likes { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; public CustomDataObject() { diff --git a/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample1_cs.txt b/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample1_cs.txt index 27bcc355a..7237a75bd 100644 --- a/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample1_cs.txt +++ b/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample1_cs.txt @@ -4,11 +4,11 @@ public class StringOrIntTemplateSelector : DataTemplateSelector { // Define the (currently empty) data templates to return // These will be "filled-in" in the XAML code. - public DataTemplate StringTemplate { get; set; } + public DataTemplate? StringTemplate { get; set; } - public DataTemplate IntTemplate { get; set; } + public DataTemplate? IntTemplate { get; set; } - protected override DataTemplate SelectTemplateCore(object item) + protected override DataTemplate? SelectTemplateCore(object item) { // Return the correct data template based on the item's type. if (item.GetType() == typeof(String)) diff --git a/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample2_cs.txt b/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample2_cs.txt index 0cf95a7a2..e9fdef9c2 100644 --- a/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample2_cs.txt +++ b/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample2_cs.txt @@ -2,10 +2,10 @@ public class MyDataTemplateSelector : DataTemplateSelector { - public DataTemplate Normal { get; set; } - public DataTemplate Accent { get; set; } + public DataTemplate? Normal { get; set; } + public DataTemplate? Accent { get; set; } - protected override DataTemplate SelectTemplateCore(object item) + protected override DataTemplate? SelectTemplateCore(object item) { if ((int)item % 2 == 0) { diff --git a/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample3_cs.txt b/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample3_cs.txt index 4abc8a6f1..fe96f263e 100644 --- a/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample3_cs.txt +++ b/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample3_cs.txt @@ -40,16 +40,19 @@ private void InitializeData() private void Animated_GotItem(object sender, RoutedEventArgs e) { - var item = sender as FrameworkElement; + if (sender is not Button senderBtn) + { + return; + } + // When the clicked item has been recieved, bring it to the middle of the viewport. - item.StartBringIntoView(new BringIntoViewOptions() + senderBtn.StartBringIntoView(new BringIntoViewOptions() { VerticalAlignmentRatio = 0.5, AnimationDesired = true, }); // Update corresponding rectangle with selected color - Button senderBtn = sender as Button; colorRectangle.Fill = senderBtn.Background; } @@ -84,9 +87,13 @@ private void OnElementPrepared(Microsoft.UI.Xaml.Controls.ItemsRepeater sender, and sets the rectangle to match its color. */ private void Animated_ScrollViewer_ViewChanging(object sender, ScrollViewerViewChangingEventArgs e) { - Button SelectedItem = GetSelectedItemFromViewport() as Button; + if (GetSelectedItemFromViewport() is not Button selectedItem) + { + return; + } + // Update corresponding rectangle with selected color - colorRectangle.Fill = SelectedItem.Background; + colorRectangle.Fill = selectedItem.Background; } // The remainder of these functions are helper functions for the ViewChanging function: @@ -107,7 +114,7 @@ private int GetSelectedIndexFromViewport() } // Return item that's at the center of the viewport. -private object GetSelectedItemFromViewport() +private object? GetSelectedItemFromViewport() { var selectedIndex = GetSelectedIndexFromViewport(); var selectedElement = animatedScrollRepeater.TryGetElement(selectedIndex) as Button; diff --git a/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample4_cs.txt b/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample4_cs.txt index 243cabe48..3a7501b85 100644 --- a/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample4_cs.txt +++ b/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample4_cs.txt @@ -4,12 +4,13 @@ public class Recipe { public int Num { get; set; } - public string Ingredients { get; set; } - public List IngList { get; set; } - public string Name { get; set; } - public string Color { get; set; } - public int numIngredients { - get + public string Ingredients { get; set; } = string.Empty; + public List IngList { get; set; } = []; + public string Name { get; set; } = string.Empty; + public string Color { get; set; } = string.Empty; + public int numIngredients + { + get { return IngList.Count(); } @@ -18,7 +19,7 @@ public class Recipe public void RandomizeIngredients() { // To give the items different heights for visual variety, give recipes - // random numbers of random "extra" ingredients + // random numbers of random "extra" ingredients Random rndNum = new Random(); Random rndIng = new Random(); @@ -33,7 +34,7 @@ public class Recipe for (int i =0; i < rndNum.Next(0,4); i++) { string newIng = extras[rndIng.Next(0, 6)]; - // If the ingredient is not already present in the recipe, add it + // If the ingredient is not already present in the recipe, add it if (!IngList.Contains(newIng)) { Ingredients += "\n" + newIng; @@ -52,8 +53,8 @@ public class Recipe well for a full tutorial on how to implement this type of class. */ public class MyItemsSource : IList, - Microsoft.UI.Xaml.Controls.IKeyIndexMapping, - INotifyCollectionChanged + Microsoft.UI.Xaml.Controls.IKeyIndexMapping, + INotifyCollectionChanged { private List inner = new List(); @@ -72,15 +73,14 @@ public class MyItemsSource : IList, if (CollectionChanged != null) { - CollectionChanged(this, - new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); + CollectionChanged?.Invoke( + this, + new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } //... - #region IKeyIndexMapping - public string KeyFromIndex(int index) { return inner[index].Num.ToString(); @@ -131,7 +131,7 @@ private void InitializeData() string grainOption = grains[rnd.Next(0, 6)]; string proteinOption = proteins[rnd.Next(0, 6)]; rec.Ingredients = "\n" + fruitOption + "\n" + vegOption + "\n" + - grainOption + "\n" + proteinOption; + grainOption + "\n" + proteinOption; rec.IngList = new List() { fruitOption, vegOption, grainOption, proteinOption }; rec.RandomizeIngredients(); } @@ -174,9 +174,10 @@ private void UpdateSortAndFilter() { // This is a Linq query that fetches all Recipes containing the ingredient // typed into the filter text box. - var filteredTypes = staticRecipeData.Where(i => i.Ingredients.Contains( - FilterRecipes.Text, - StringComparison.InvariantCultureIgnoreCase)); + var filteredTypes = staticRecipeData + .Where(i => i.Ingredients.Contains( + FilterRecipes.Text, + StringComparison.InvariantCultureIgnoreCase)); // After filtering, sort the collection var sortedFilteredTypes = IsSortDescending ? filteredTypes.OrderByDescending(i => i.numIngredients) : diff --git a/WinUIGallery/Samples/SampleCode/ListView/ListViewSample1_cs.txt b/WinUIGallery/Samples/SampleCode/ListView/ListViewSample1_cs.txt index 8e7e060f8..7110703e4 100644 --- a/WinUIGallery/Samples/SampleCode/ListView/ListViewSample1_cs.txt +++ b/WinUIGallery/Samples/SampleCode/ListView/ListViewSample1_cs.txt @@ -5,9 +5,9 @@ public class Contact { - public string FirstName { get; private set; } - public string LastName { get; private set; } - public string Company { get; private set; } + public string FirstName { get; private set; } = string.Empty; + public string LastName { get; private set; } = string.Empty; + public string Company { get; private set; } = string.Empty; public string Name => FirstName + " " + LastName; public Contact(string firstName, string lastName, string company) diff --git a/WinUIGallery/Samples/SampleCode/ListView/ListViewSample2_cs.txt b/WinUIGallery/Samples/SampleCode/ListView/ListViewSample2_cs.txt index ca697935a..5373118a2 100644 --- a/WinUIGallery/Samples/SampleCode/ListView/ListViewSample2_cs.txt +++ b/WinUIGallery/Samples/SampleCode/ListView/ListViewSample2_cs.txt @@ -27,6 +27,7 @@ public class GroupInfoList : List public GroupInfoList(IEnumerable items) : base(items) { } + public object Key { get; set; } public override string ToString() @@ -37,20 +38,20 @@ public class GroupInfoList : List // Contact class definition: public class Contact +{ + public string FirstName { get; private set; } = string.Empty; + public string LastName { get; private set; } = string.Empty; + public string Company { get; private set; } = string.Empty; + public string Name => FirstName + " " + LastName; + + public Contact(string firstName, string lastName, string company) { - public string FirstName { get; private set; } - public string LastName { get; private set; } - public string Company { get; private set; } - public string Name => FirstName + " " + LastName; - - public Contact(string firstName, string lastName, string company) - { - FirstName = firstName; - LastName = lastName; - Company = company; - } - - // ... Methods ... + FirstName = firstName; + LastName = lastName; + Company = company; + } + + // ... Methods ... } ContactsCVS.Source = await Contact.GetContactsGroupedAsync(); \ No newline at end of file diff --git a/WinUIGallery/Samples/SampleCode/Motion/AnimationInterop/AnimationInteropSample1_cs.txt b/WinUIGallery/Samples/SampleCode/Motion/AnimationInterop/AnimationInteropSample1_cs.txt index ddb8fc661..58574e9ea 100644 --- a/WinUIGallery/Samples/SampleCode/Motion/AnimationInterop/AnimationInteropSample1_cs.txt +++ b/WinUIGallery/Samples/SampleCode/Motion/AnimationInterop/AnimationInteropSample1_cs.txt @@ -1,5 +1,5 @@ Compositor _compositor = App.CurrentWindow.Compositor; -SpringVector3NaturalMotionAnimation _springAnimation; +SpringVector3NaturalMotionAnimation? _springAnimation; private void CreateOrUpdateSpringAnimation(float finalValue) { @@ -17,7 +17,7 @@ private void element_PointerEntered(object sender, PointerRoutedEventArgs e) // Scale up to 1.5 CreateOrUpdateSpringAnimation(1.5f); - (sender as UIElement).StartAnimation(_springAnimation); + (sender as UIElement)?.StartAnimation(_springAnimation); } private void element_PointerExited(object sender, PointerRoutedEventArgs e) @@ -25,5 +25,5 @@ private void element_PointerExited(object sender, PointerRoutedEventArgs e) // Scale back down to 1.0 CreateOrUpdateSpringAnimation(1.0f); - (sender as UIElement).StartAnimation(_springAnimation); + (sender as UIElement)?.StartAnimation(_springAnimation); } \ No newline at end of file diff --git a/WinUIGallery/Samples/SampleCode/Motion/ConnectedAnimation/ConnectedAnimationSample1_cs.txt b/WinUIGallery/Samples/SampleCode/Motion/ConnectedAnimation/ConnectedAnimationSample1_cs.txt index 9fcfc38f9..11985ada5 100644 --- a/WinUIGallery/Samples/SampleCode/Motion/ConnectedAnimation/ConnectedAnimationSample1_cs.txt +++ b/WinUIGallery/Samples/SampleCode/Motion/ConnectedAnimation/ConnectedAnimationSample1_cs.txt @@ -5,7 +5,7 @@ // COLLECTION PAGE public sealed partial class CollectionPage : Page { - CustomDataObject _storeditem; + CustomDataObject? _storeditem; public CollectionPage() { @@ -66,7 +66,8 @@ public sealed partial class CollectionPage : Page // DETAILED PAGE public sealed partial class DetailedInfoPage : Page { - public CustomDataObject DetailedObject { get; set; } + public CustomDataObject? DetailedObject { get; set; } + public DetailedInfoPage() { this.InitializeComponent(); diff --git a/WinUIGallery/Samples/SampleCode/NavigationView/NavigationViewSample5_cs.txt b/WinUIGallery/Samples/SampleCode/NavigationView/NavigationViewSample5_cs.txt index 3f55cb269..a67719bb2 100644 --- a/WinUIGallery/Samples/SampleCode/NavigationView/NavigationViewSample5_cs.txt +++ b/WinUIGallery/Samples/SampleCode/NavigationView/NavigationViewSample5_cs.txt @@ -9,8 +9,8 @@ public class CategoryBase { } public class Category : CategoryBase { - public string Name { get; set; } - public string Tooltip { get; set; } + public string Name { get; set; } = string.Empty; + public string Tooltip { get; set; } = string.Empty; public Symbol Glyph { get; set; } } @@ -24,8 +24,9 @@ public class Header : CategoryBase [ContentProperty(Name = "ItemTemplate")] class MenuItemTemplateSelector : DataTemplateSelector { - public DataTemplate ItemTemplate { get; set; } - protected override DataTemplate SelectTemplateCore(object item) + public DataTemplate? ItemTemplate { get; set; } + + protected override DataTemplate? SelectTemplateCore(object item) { return item is Separator ? SeparatorTemplate : item is Header ? HeaderTemplate : ItemTemplate; } diff --git a/WinUIGallery/Samples/SampleCode/ScrollView/ScrollViewSample3_DefaultAnimation_cs.txt b/WinUIGallery/Samples/SampleCode/ScrollView/ScrollViewSample3_DefaultAnimation_cs.txt index da04001ff..fc2a43cb7 100644 --- a/WinUIGallery/Samples/SampleCode/ScrollView/ScrollViewSample3_DefaultAnimation_cs.txt +++ b/WinUIGallery/Samples/SampleCode/ScrollView/ScrollViewSample3_DefaultAnimation_cs.txt @@ -2,7 +2,7 @@ private void ScrollView_ScrollAnimationStarting(ScrollView sender, ScrollingScrollAnimationStartingEventArgs e) { // Cast the animation from the event arguments to a Vector3KeyFrameAnimation. - Vector3KeyFrameAnimation stockKeyFrameAnimation = e.Animation as Vector3KeyFrameAnimation; + Vector3KeyFrameAnimation? stockKeyFrameAnimation = e.Animation as Vector3KeyFrameAnimation; // Check if the animation is of the correct type. if (stockKeyFrameAnimation != null) diff --git a/WinUIGallery/Samples/SampleCode/ScrollView/ScrollViewSample3_TeleportationAnimation_cs.txt b/WinUIGallery/Samples/SampleCode/ScrollView/ScrollViewSample3_TeleportationAnimation_cs.txt index 52fcd8a93..4be0d76c4 100644 --- a/WinUIGallery/Samples/SampleCode/ScrollView/ScrollViewSample3_TeleportationAnimation_cs.txt +++ b/WinUIGallery/Samples/SampleCode/ScrollView/ScrollViewSample3_TeleportationAnimation_cs.txt @@ -2,7 +2,7 @@ private void ScrollView_ScrollAnimationStarting(ScrollView sender, ScrollingScrollAnimationStartingEventArgs e) { // Cast the animation from the event arguments to a Vector3KeyFrameAnimation. - Vector3KeyFrameAnimation stockKeyFrameAnimation = e.Animation as Vector3KeyFrameAnimation; + Vector3KeyFrameAnimation? stockKeyFrameAnimation = e.Animation as Vector3KeyFrameAnimation; // Check if the animation is of the correct type. if (stockKeyFrameAnimation != null) diff --git a/WinUIGallery/Samples/SampleCode/TabView/TabViewBasicSample_cs.txt b/WinUIGallery/Samples/SampleCode/TabView/TabViewBasicSample_cs.txt index eaed5d2e9..2633f6d6e 100644 --- a/WinUIGallery/Samples/SampleCode/TabView/TabViewBasicSample_cs.txt +++ b/WinUIGallery/Samples/SampleCode/TabView/TabViewBasicSample_cs.txt @@ -2,7 +2,7 @@ { for (int i = 0; i < 3; i++) { - (sender as TabView).TabItems.Add(CreateNewTab(i)); + (sender as TabView)?.TabItems.Add(CreateNewTab(i)); } } diff --git a/WinUIGallery/Samples/SampleCode/TabView/TabViewKeyboardAcceleratorSample_cs.txt b/WinUIGallery/Samples/SampleCode/TabView/TabViewKeyboardAcceleratorSample_cs.txt index df407bd3f..8cb24d1b5 100644 --- a/WinUIGallery/Samples/SampleCode/TabView/TabViewKeyboardAcceleratorSample_cs.txt +++ b/WinUIGallery/Samples/SampleCode/TabView/TabViewKeyboardAcceleratorSample_cs.txt @@ -1,27 +1,37 @@ private void NewTabKeyboardAccelerator_Invoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args) { - var senderTabView = args.Element as TabView; + if (ars.Element is not TabView senderTabView) + { + return; + } + senderTabView.TabItems.Add(CreateNewTab(senderTabView.TabItems.Count)); - args.Handled = true; + args.Handled = true; } private void CloseSelectedTabKeyboardAccelerator_Invoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args) { - var InvokedTabView = (args.Element as TabView); + if (args.Element is not TabView invokedTabView) + { + return; + } // Only close the selected tab if it is closeable - if (((TabViewItem)InvokedTabView.SelectedItem).IsClosable) + if ((invokedTabView.SelectedItem as TabViewItem)?.IsClosable is true) { - InvokedTabView.TabItems.Remove(InvokedTabView.SelectedItem); + invokedTabView.TabItems.Remove(invokedTabView.SelectedItem); } - args.Handled = true; + args.Handled = true; } private void NavigateToNumberedTabKeyboardAccelerator_Invoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args) { - var InvokedTabView = (args.Element as TabView); + if (args.Element is not TabView invokedTabView) + { + return; + } int tabToSelect = 0; @@ -53,15 +63,15 @@ private void NavigateToNumberedTabKeyboardAccelerator_Invoked(KeyboardAccelerato break; case Windows.System.VirtualKey.Number9: // Select the last tab - tabToSelect = InvokedTabView.TabItems.Count - 1; + tabToSelect = invokedTabView.TabItems.Count - 1; break; } // Only select the tab if it is in the list - if (tabToSelect < InvokedTabView.TabItems.Count) + if (tabToSelect < invokedTabView.TabItems.Count) { - InvokedTabView.SelectedIndex = tabToSelect; + invokedTabView.SelectedIndex = tabToSelect; } - args.Handled = true; + args.Handled = true; } \ No newline at end of file diff --git a/WinUIGallery/Samples/SampleCode/Text/RichEditBox/RichEditBoxSample3_cs.txt b/WinUIGallery/Samples/SampleCode/Text/RichEditBox/RichEditBoxSample3_cs.txt index 9de50499c..2c7b6a1e1 100644 --- a/WinUIGallery/Samples/SampleCode/Text/RichEditBox/RichEditBoxSample3_cs.txt +++ b/WinUIGallery/Samples/SampleCode/Text/RichEditBox/RichEditBoxSample3_cs.txt @@ -116,9 +116,13 @@ private void FindBoxHighlightMatches() private void FindBoxRemoveHighlights() { + if (editor.Background is not SolidColorBrush defaultBackground || + editor.Foreground is not SolidColorBrush defaultForeground) + { + return; + } + ITextRange documentRange = editor.Document.GetRange(0, TextConstants.MaxUnitCount); - SolidColorBrush defaultBackground = editor.Background as SolidColorBrush; - SolidColorBrush defaultForeground = editor.Foreground as SolidColorBrush; documentRange.CharacterFormat.BackgroundColor = defaultBackground.Color; documentRange.CharacterFormat.ForegroundColor = defaultForeground.Color; diff --git a/WinUIGallery/Samples/SampleCode/Text/RichEditBox/RichEditBoxSample4_cs.txt b/WinUIGallery/Samples/SampleCode/Text/RichEditBox/RichEditBoxSample4_cs.txt index f07830f35..35f5278e7 100644 --- a/WinUIGallery/Samples/SampleCode/Text/RichEditBox/RichEditBoxSample4_cs.txt +++ b/WinUIGallery/Samples/SampleCode/Text/RichEditBox/RichEditBoxSample4_cs.txt @@ -1,6 +1,10 @@ private void Menu_Opening(object sender, object e) { - CommandBarFlyout myFlyout = sender as CommandBarFlyout; + if (sender is not CommandBarFlyout myFlyout) + { + return; + } + if (myFlyout.Target == REBCustom) { AppBarButton myButton = new AppBarButton(); diff --git a/WinUIGallery/Samples/SampleCode/TreeView/TreeViewDataBindingSample_cs.txt b/WinUIGallery/Samples/SampleCode/TreeView/TreeViewDataBindingSample_cs.txt index 9234dc854..4daab2db0 100644 --- a/WinUIGallery/Samples/SampleCode/TreeView/TreeViewDataBindingSample_cs.txt +++ b/WinUIGallery/Samples/SampleCode/TreeView/TreeViewDataBindingSample_cs.txt @@ -71,7 +71,7 @@ namespace YourNamespace } // Name of the item (displayed in the TreeView). - public string Name { get; set; } + public string Name { get; set; } = string.Empty; // Type of the item (Folder or File). public ExplorerItemType Type { get; set; } diff --git a/WinUIGallery/Samples/SampleCode/TreeView/TreeViewTemplateSelectorSample_cs.txt b/WinUIGallery/Samples/SampleCode/TreeView/TreeViewTemplateSelectorSample_cs.txt index 047c92389..de3303ef0 100644 --- a/WinUIGallery/Samples/SampleCode/TreeView/TreeViewTemplateSelectorSample_cs.txt +++ b/WinUIGallery/Samples/SampleCode/TreeView/TreeViewTemplateSelectorSample_cs.txt @@ -62,7 +62,7 @@ namespace YourNamespace File, } - public string Name { get; set; } + public string Name { get; set; } = string.Empty; public ExplorerItemType Type { get; set; } public ObservableCollection Children { get; set; } = new ObservableCollection(); } @@ -70,13 +70,13 @@ namespace YourNamespace class ExplorerItemTemplateSelector : DataTemplateSelector { // Template to use for folder items in the TreeView. - public DataTemplate FolderTemplate { get; set; } + public DataTemplate? FolderTemplate { get; set; } // Template to use for file items in the TreeView. - public DataTemplate FileTemplate { get; set; } + public DataTemplate? FileTemplate { get; set; } // Determines which template to use for each item in the TreeView based on its type. - protected override DataTemplate SelectTemplateCore(object item) + protected override DataTemplate? SelectTemplateCore(object item) { // Cast the item to the ExplorerItem type. var explorerItem = (ExplorerItem)item; diff --git a/WinUIGallery/Samples/SamplePages/CardPage.xaml.cs b/WinUIGallery/Samples/SamplePages/CardPage.xaml.cs index 9094a114e..92ac1d781 100644 --- a/WinUIGallery/Samples/SamplePages/CardPage.xaml.cs +++ b/WinUIGallery/Samples/SamplePages/CardPage.xaml.cs @@ -58,7 +58,7 @@ private void Animation_Completed(ConnectedAnimation sender, object args) private void TipsGrid_ItemClick(object sender, ItemClickEventArgs e) { - ConnectedAnimation animation = null; + ConnectedAnimation? animation = null; // Get the collection item corresponding to the clicked item. if (collection.ContainerFromItem(e.ClickedItem) is GridViewItem container) @@ -75,6 +75,6 @@ private void TipsGrid_ItemClick(object sender, ItemClickEventArgs e) SmokeGrid.Visibility = Visibility.Visible; - animation.TryStart(destinationElement); + animation?.TryStart(destinationElement); } } diff --git a/WinUIGallery/Samples/SamplePages/CollectionPage.xaml.cs b/WinUIGallery/Samples/SamplePages/CollectionPage.xaml.cs index a08dea137..886579a65 100644 --- a/WinUIGallery/Samples/SamplePages/CollectionPage.xaml.cs +++ b/WinUIGallery/Samples/SamplePages/CollectionPage.xaml.cs @@ -13,7 +13,7 @@ namespace WinUIGallery.SamplePages; public sealed partial class CollectionPage : Page { - CustomDataObject _storeditem; + CustomDataObject? _storeditem; public CollectionPage() { diff --git a/WinUIGallery/Samples/SamplePages/DetailedInfoPage.xaml.cs b/WinUIGallery/Samples/SamplePages/DetailedInfoPage.xaml.cs index 450be8b26..263e761f5 100644 --- a/WinUIGallery/Samples/SamplePages/DetailedInfoPage.xaml.cs +++ b/WinUIGallery/Samples/SamplePages/DetailedInfoPage.xaml.cs @@ -11,7 +11,8 @@ namespace WinUIGallery.SamplePages; public sealed partial class DetailedInfoPage : Page { - public CustomDataObject DetailedObject { get; set; } + public CustomDataObject? DetailedObject { get; set; } + public DetailedInfoPage() { this.InitializeComponent(); diff --git a/WinUIGallery/Samples/SamplePages/SamplePage1.xaml.cs b/WinUIGallery/Samples/SamplePages/SamplePage1.xaml.cs index a63d1bffa..5e1c3b777 100644 --- a/WinUIGallery/Samples/SamplePages/SamplePage1.xaml.cs +++ b/WinUIGallery/Samples/SamplePages/SamplePage1.xaml.cs @@ -15,7 +15,7 @@ public SamplePage1() this.InitializeComponent(); } - public void PrepareConnectedAnimation(ConnectedAnimationConfiguration config) + public void PrepareConnectedAnimation(ConnectedAnimationConfiguration? config) { var anim = ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("ForwardConnectedAnimation", SourceElement); diff --git a/WinUIGallery/Samples/SamplePages/SamplePage2.xaml.cs b/WinUIGallery/Samples/SamplePages/SamplePage2.xaml.cs index 97c108427..b7b9e2950 100644 --- a/WinUIGallery/Samples/SamplePages/SamplePage2.xaml.cs +++ b/WinUIGallery/Samples/SamplePages/SamplePage2.xaml.cs @@ -15,7 +15,7 @@ public SamplePage2() this.InitializeComponent(); } - public void PrepareConnectedAnimation(ConnectedAnimationConfiguration config) + public void PrepareConnectedAnimation(ConnectedAnimationConfiguration? config) { var anim = ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("BackwardConnectedAnimation", DestinationElement); diff --git a/WinUIGallery/Samples/SamplePages/SampleSystemBackdropsWindow.xaml.cs b/WinUIGallery/Samples/SamplePages/SampleSystemBackdropsWindow.xaml.cs index 6c982ea76..dbe7b68e4 100644 --- a/WinUIGallery/Samples/SamplePages/SampleSystemBackdropsWindow.xaml.cs +++ b/WinUIGallery/Samples/SamplePages/SampleSystemBackdropsWindow.xaml.cs @@ -24,9 +24,9 @@ public BackdropType[] AllowedBackdrops } BackdropType currentBackdrop; - MicaController micaController; - DesktopAcrylicController acrylicController; - SystemBackdropConfiguration configurationSource; + MicaController? micaController; + DesktopAcrylicController? acrylicController; + SystemBackdropConfiguration? configurationSource; public SampleSystemBackdropsWindow() { @@ -203,8 +203,11 @@ private void Window_ThemeChanged(FrameworkElement sender, object args) private void SetConfigurationSourceTheme() { - configurationSource.IsHighContrast = ThemeSettings.CreateForWindowId(this.AppWindow.Id).HighContrast; - configurationSource.Theme = (SystemBackdropTheme)((FrameworkElement)Content).ActualTheme; + if (configurationSource != null) + { + configurationSource.IsHighContrast = ThemeSettings.CreateForWindowId(this.AppWindow.Id).HighContrast; + configurationSource.Theme = (SystemBackdropTheme)((FrameworkElement)Content).ActualTheme; + } } private void BackdropComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) diff --git a/WinUIGallery/Samples/SamplePages/TabViewWindowingSamplePage.xaml.cs b/WinUIGallery/Samples/SamplePages/TabViewWindowingSamplePage.xaml.cs index 7378f067c..1d32fc99e 100644 --- a/WinUIGallery/Samples/SamplePages/TabViewWindowingSamplePage.xaml.cs +++ b/WinUIGallery/Samples/SamplePages/TabViewWindowingSamplePage.xaml.cs @@ -12,8 +12,8 @@ namespace WinUIGallery.SamplePages; public sealed partial class TabViewWindowingSamplePage : Page { private const string DataIdentifier = "MyTabItem"; - private Win32WindowHelper win32WindowHelper; - private Window tabTearOutWindow = null; + private Win32WindowHelper? win32WindowHelper; + private Window? tabTearOutWindow = null; public TabViewWindowingSamplePage() { @@ -30,7 +30,11 @@ public void SetupWindowMinSize(Window window) private void TabViewWindowingSamplePage_Loaded(object sender, RoutedEventArgs e) { - var currentWindow = WindowHelper.GetWindowForElement(this); + if (WindowHelper.GetWindowForElement(this) is not Window currentWindow) + { + return; + } + currentWindow.ExtendsContentIntoTitleBar = true; currentWindow.SetTitleBar(CustomDragRegion); CustomDragRegion.MinWidth = 188; @@ -98,7 +102,7 @@ private void Tabs_ExternalTornOutTabsDropped(TabView sender, TabViewExternalTorn } } - private TabView GetParentTabView(TabViewItem tab) + private TabView? GetParentTabView(TabViewItem tab) { DependencyObject current = tab; @@ -145,7 +149,7 @@ private void Tabs_TabCloseRequested(TabView sender, TabViewTabCloseRequestedEven if (sender.TabItems.Count == 0) { - WindowHelper.GetWindowForElement(this).Close(); + WindowHelper.GetWindowForElement(this)?.Close(); } } } diff --git a/WinUIGallery/Samples/SamplePages/TitleBarWindow.xaml.cs b/WinUIGallery/Samples/SamplePages/TitleBarWindow.xaml.cs index 21f38e9c2..af1fc6bb2 100644 --- a/WinUIGallery/Samples/SamplePages/TitleBarWindow.xaml.cs +++ b/WinUIGallery/Samples/SamplePages/TitleBarWindow.xaml.cs @@ -39,7 +39,7 @@ private void navView_SelectionChanged(NavigationView sender, NavigationViewSelec string selectedItemTag = ((string)selectedItem.Tag); sender.Header = "Sample Page " + selectedItemTag.Substring(selectedItemTag.Length - 1); string pageName = "WinUIGallery.SamplePages." + selectedItemTag; - Type pageType = Type.GetType(pageName); + Type? pageType = Type.GetType(pageName); navFrame.Navigate(pageType); } } diff --git a/WinUIGallery/WinUIGallery.csproj b/WinUIGallery/WinUIGallery.csproj index 5fe5992f7..24479ebd6 100644 --- a/WinUIGallery/WinUIGallery.csproj +++ b/WinUIGallery/WinUIGallery.csproj @@ -44,6 +44,7 @@ true Assets\Tiles\GalleryIcon.ico + enable