Fix C# warnings

A continuation of my last PR
This commit is contained in:
Rose 2022-08-30 18:50:33 -04:00
commit 2798042dbb
38 changed files with 150 additions and 375 deletions

View file

@ -30,7 +30,7 @@ namespace CalculatorApp
{ {
namespace ApplicationResourceKeys namespace ApplicationResourceKeys
{ {
public static partial class Globals public static class Globals
{ {
public static readonly string AppMinWindowHeight = "AppMinWindowHeight"; public static readonly string AppMinWindowHeight = "AppMinWindowHeight";
public static readonly string AppMinWindowWidth = "AppMinWindowWidth"; public static readonly string AppMinWindowWidth = "AppMinWindowWidth";
@ -253,8 +253,7 @@ namespace CalculatorApp
int newWindowId = ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread()); int newWindowId = ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread());
ActivationViewSwitcher activationViewSwitcher = null; ActivationViewSwitcher activationViewSwitcher = null;
var activateEventArgs = (args as IViewSwitcherProvider); if (args is IViewSwitcherProvider activateEventArgs)
if (activateEventArgs != null)
{ {
activationViewSwitcher = activateEventArgs.ViewSwitcher; activationViewSwitcher = activateEventArgs.ViewSwitcher;
} }
@ -266,8 +265,7 @@ namespace CalculatorApp
} }
else else
{ {
var activatedEventArgs = (args as IApplicationViewActivatedEventArgs); if ((args is IApplicationViewActivatedEventArgs activatedEventArgs) && (activatedEventArgs.CurrentlyShownApplicationViewId != 0))
if ((activatedEventArgs != null) && (activatedEventArgs.CurrentlyShownApplicationViewId != 0))
{ {
// CSHARP_MIGRATION_ANNOTATION: // CSHARP_MIGRATION_ANNOTATION:
// here we don't use ContinueWith() to interpret origin code because we would like to // here we don't use ContinueWith() to interpret origin code because we would like to
@ -294,8 +292,7 @@ namespace CalculatorApp
else else
{ {
ActivationViewSwitcher activationViewSwitcher = null; ActivationViewSwitcher activationViewSwitcher = null;
var activateEventArgs = (args as IViewSwitcherProvider); if (args is IViewSwitcherProvider activateEventArgs)
if (activateEventArgs != null)
{ {
activationViewSwitcher = activateEventArgs.ViewSwitcher; activationViewSwitcher = activateEventArgs.ViewSwitcher;
} }
@ -334,14 +331,13 @@ namespace CalculatorApp
// for tablet mode: since system view activation policy is disabled so do ShowAsStandaloneAsync if activationViewSwitcher exists in // for tablet mode: since system view activation policy is disabled so do ShowAsStandaloneAsync if activationViewSwitcher exists in
// activationArgs // activationArgs
ActivationViewSwitcher activationViewSwitcher = null; ActivationViewSwitcher activationViewSwitcher = null;
var activateEventArgs = (args as IViewSwitcherProvider); if (args is IViewSwitcherProvider activateEventArgs)
if (activateEventArgs != null)
{ {
activationViewSwitcher = activateEventArgs.ViewSwitcher; activationViewSwitcher = activateEventArgs.ViewSwitcher;
} }
if (activationViewSwitcher != null) if (activationViewSwitcher != null)
{ {
var viewId = (args as IApplicationViewActivatedEventArgs).CurrentlyShownApplicationViewId; var viewId = ((IApplicationViewActivatedEventArgs)args).CurrentlyShownApplicationViewId;
if (viewId != 0) if (viewId != 0)
{ {
_ = activationViewSwitcher.ShowAsStandaloneAsync(viewId); _ = activationViewSwitcher.ShowAsStandaloneAsync(viewId);
@ -495,7 +491,7 @@ namespace CalculatorApp
try try
{ {
bool removed = m_secondaryWindows.Remove(viewId); bool removed = m_secondaryWindows.Remove(viewId);
Debug.Assert(removed != false, "Window does not exist in the list"); Debug.Assert(removed, "Window does not exist in the list");
} }
finally finally
{ {

View file

@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved. // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. // Licensed under the MIT License.
using System; using System;
@ -44,10 +44,10 @@ namespace CalculatorApp
// restore the selection to the way we wanted it to begin with // restore the selection to the way we wanted it to begin with
if (CurrentPosition >= 0 && CurrentPosition < m_source.Count) if (CurrentPosition >= 0 && CurrentPosition < m_source.Count)
{ {
Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() => Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{ {
CurrentChanged?.Invoke(this, null); CurrentChanged?.Invoke(this, null);
})).AsTask().Wait(); }).AsTask().Wait();
} }
return false; return false;
} }
@ -196,10 +196,6 @@ namespace CalculatorApp
public sealed class AlwaysSelectedCollectionViewConverter : Windows.UI.Xaml.Data.IValueConverter public sealed class AlwaysSelectedCollectionViewConverter : Windows.UI.Xaml.Data.IValueConverter
{ {
public AlwaysSelectedCollectionViewConverter()
{
}
public object Convert(object value, Type targetType, object parameter, string language) public object Convert(object value, Type targetType, object parameter, string language)
{ {
if (value is IList result) if (value is IList result)

View file

@ -115,10 +115,6 @@ namespace CalculatorApp
public sealed class KeyboardShortcutManager : DependencyObject public sealed class KeyboardShortcutManager : DependencyObject
{ {
public KeyboardShortcutManager()
{
}
public static readonly DependencyProperty CharacterProperty = public static readonly DependencyProperty CharacterProperty =
DependencyProperty.RegisterAttached( DependencyProperty.RegisterAttached(
"Character", "Character",
@ -484,13 +480,8 @@ namespace CalculatorApp
// Writer lock for the static maps // Writer lock for the static maps
lock (s_keyboardShortcutMapLockMutex) lock (s_keyboardShortcutMapLockMutex)
{ {
Control control = (target as ButtonBase); // Handling Ctrl+E shortcut for Date Calc, target would be NavigationView^ in that case
Control control = (target as ButtonBase) ?? (Control)(target as MUXC.NavigationView);
if (control == null)
{
// Handling Ctrl+E shortcut for Date Calc, target would be NavigationView^ in that case
control = (target as MUXC.NavigationView);
}
int viewId = Utilities.GetWindowId(); int viewId = Utilities.GetWindowId();
@ -580,7 +571,7 @@ namespace CalculatorApp
private static bool CanNavigateModeByShortcut(MUXC.NavigationView navView, object nvi private static bool CanNavigateModeByShortcut(MUXC.NavigationView navView, object nvi
, ApplicationViewModel vm, ViewMode toMode) , ApplicationViewModel vm, ViewMode toMode)
{ {
if (nvi != null && nvi is NavCategory navCategory) if (nvi is NavCategory navCategory)
{ {
return navCategory.IsEnabled return navCategory.IsEnabled
&& navView.Visibility == Visibility.Visible && navView.Visibility == Visibility.Visible
@ -601,21 +592,18 @@ namespace CalculatorApp
{ {
if (itemRef.Target is MUXC.NavigationView item) if (itemRef.Target is MUXC.NavigationView item)
{ {
var navView = item; var menuItems = ((List<object>)item.MenuItemsSource);
var menuItems = ((List<object>)navView.MenuItemsSource);
if (menuItems != null) if (menuItems != null)
{ {
var vm = (navView.DataContext as ApplicationViewModel); if (item.DataContext is ApplicationViewModel vm)
if (null != vm)
{ {
ViewMode realToMode = toMode.HasValue ? toMode.Value : NavCategoryStates.GetViewModeForVirtualKey(((MyVirtualKey)key)); ViewMode realToMode = toMode ?? NavCategoryStates.GetViewModeForVirtualKey(((MyVirtualKey)key));
var nvi = menuItems[NavCategoryStates.GetFlatIndex(realToMode)]; var nvi = menuItems[NavCategoryStates.GetFlatIndex(realToMode)];
if (CanNavigateModeByShortcut(navView, nvi, vm, realToMode)) if (CanNavigateModeByShortcut(item, nvi, vm, realToMode))
{ {
vm.Mode = realToMode; vm.Mode = realToMode;
navView.SelectedItem = nvi; item.SelectedItem = nvi;
} }
} }
} }

View file

@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved. // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. // Licensed under the MIT License.
using System; using System;
@ -8,9 +8,6 @@ namespace CalculatorApp
{ {
public sealed class ValidSelectedItemConverter : Windows.UI.Xaml.Data.IValueConverter public sealed class ValidSelectedItemConverter : Windows.UI.Xaml.Data.IValueConverter
{ {
public ValidSelectedItemConverter()
{ }
public object Convert(object value, Type targetType, object parameter, string language) public object Convert(object value, Type targetType, object parameter, string language)
{ {
// Pass through as we don't want to change the value from the source // Pass through as we don't want to change the value from the source
@ -31,9 +28,6 @@ namespace CalculatorApp
public sealed class ValidSelectedIndexConverter : Windows.UI.Xaml.Data.IValueConverter public sealed class ValidSelectedIndexConverter : Windows.UI.Xaml.Data.IValueConverter
{ {
public ValidSelectedIndexConverter()
{ }
public object Convert(object value, Type targetType, object parameter, string language) public object Convert(object value, Type targetType, object parameter, string language)
{ {
// Pass through as we don't want to change the value from the source // Pass through as we don't want to change the value from the source
@ -44,15 +38,12 @@ namespace CalculatorApp
{ {
// The value to be valid has to be a boxed int32 value // The value to be valid has to be a boxed int32 value
// extract that value and ensure it is valid, ie >= 0 // extract that value and ensure it is valid, ie >= 0
if (value != null) if (value is Windows.Foundation.IPropertyValue box && box.Type == Windows.Foundation.PropertyType.Int32)
{ {
if (value is Windows.Foundation.IPropertyValue box && box.Type == Windows.Foundation.PropertyType.Int32) int index = box.GetInt32();
if (index >= 0)
{ {
int index = box.GetInt32(); return value;
if (index >= 0)
{
return value;
}
} }
} }
// The value is not valid therefore stop the binding right here // The value is not valid therefore stop the binding right here

View file

@ -33,11 +33,11 @@ namespace CalculatorApp
// Using a DependencyProperty as the backing store for MinFontSize. This enables animation, styling, binding, etc... // Using a DependencyProperty as the backing store for MinFontSize. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MinFontSizeProperty = public static readonly DependencyProperty MinFontSizeProperty =
DependencyProperty.Register(nameof(MinFontSize), typeof(double), typeof(CalculationResult), new PropertyMetadata(0.0, new PropertyChangedCallback((sender, args) => DependencyProperty.Register(nameof(MinFontSize), typeof(double), typeof(CalculationResult), new PropertyMetadata(0.0, (sender, args) =>
{ {
var self = (CalculationResult)sender; var self = (CalculationResult)sender;
self.OnMinFontSizePropertyChanged((double)args.OldValue, (double)args.NewValue); self.OnMinFontSizePropertyChanged((double)args.OldValue, (double)args.NewValue);
}))); }));
public double MaxFontSize public double MaxFontSize
{ {
@ -47,11 +47,11 @@ namespace CalculatorApp
// Using a DependencyProperty as the backing store for MaxFontSize. This enables animation, styling, binding, etc... // Using a DependencyProperty as the backing store for MaxFontSize. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MaxFontSizeProperty = public static readonly DependencyProperty MaxFontSizeProperty =
DependencyProperty.Register(nameof(MaxFontSize), typeof(double), typeof(CalculationResult), new PropertyMetadata(30.0, new PropertyChangedCallback((sender, args) => DependencyProperty.Register(nameof(MaxFontSize), typeof(double), typeof(CalculationResult), new PropertyMetadata(30.0, (sender, args) =>
{ {
var self = (CalculationResult)sender; var self = (CalculationResult)sender;
self.OnMaxFontSizePropertyChanged((double)args.OldValue, (double)args.NewValue); self.OnMaxFontSizePropertyChanged((double)args.OldValue, (double)args.NewValue);
}))); }));
public Thickness DisplayMargin public Thickness DisplayMargin
{ {
@ -71,11 +71,11 @@ namespace CalculatorApp
// Using a DependencyProperty as the backing store for IsActive. This enables animation, styling, binding, etc... // Using a DependencyProperty as the backing store for IsActive. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsActiveProperty = public static readonly DependencyProperty IsActiveProperty =
DependencyProperty.Register(nameof(IsActive), typeof(bool), typeof(CalculationResult), new PropertyMetadata(default(bool), new PropertyChangedCallback((sender, args) => DependencyProperty.Register(nameof(IsActive), typeof(bool), typeof(CalculationResult), new PropertyMetadata(default(bool), (sender, args) =>
{ {
var self = (CalculationResult)sender; var self = (CalculationResult)sender;
self.OnIsActivePropertyChanged((bool)args.OldValue, (bool)args.NewValue); self.OnIsActivePropertyChanged((bool)args.OldValue, (bool)args.NewValue);
}))); }));
public string DisplayValue public string DisplayValue
{ {
@ -85,11 +85,11 @@ namespace CalculatorApp
// Using a DependencyProperty as the backing store for DisplayValue. This enables animation, styling, binding, etc... // Using a DependencyProperty as the backing store for DisplayValue. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DisplayValueProperty = public static readonly DependencyProperty DisplayValueProperty =
DependencyProperty.Register(nameof(DisplayValue), typeof(string), typeof(CalculationResult), new PropertyMetadata(string.Empty, new PropertyChangedCallback((sender, args) => DependencyProperty.Register(nameof(DisplayValue), typeof(string), typeof(CalculationResult), new PropertyMetadata(string.Empty, (sender, args) =>
{ {
var self = (CalculationResult)sender; var self = (CalculationResult)sender;
self.OnDisplayValuePropertyChanged((string)args.OldValue, (string)args.NewValue); self.OnDisplayValuePropertyChanged((string)args.OldValue, (string)args.NewValue);
}))); }));
public bool IsInError public bool IsInError
{ {
@ -99,11 +99,11 @@ namespace CalculatorApp
// Using a DependencyProperty as the backing store for IsInError. This enables animation, styling, binding, etc... // Using a DependencyProperty as the backing store for IsInError. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsInErrorProperty = public static readonly DependencyProperty IsInErrorProperty =
DependencyProperty.Register(nameof(IsInError), typeof(bool), typeof(CalculationResult), new PropertyMetadata(default(bool), new PropertyChangedCallback((sender, args) => DependencyProperty.Register(nameof(IsInError), typeof(bool), typeof(CalculationResult), new PropertyMetadata(default(bool), (sender, args) =>
{ {
var self = (CalculationResult)sender; var self = (CalculationResult)sender;
self.OnIsInErrorPropertyChanged((bool)args.OldValue, (bool)args.NewValue); self.OnIsInErrorPropertyChanged((bool)args.OldValue, (bool)args.NewValue);
}))); }));
public bool IsOperatorCommand public bool IsOperatorCommand
{ {
@ -151,7 +151,7 @@ namespace CalculatorApp
if (widthDiff > WIDTHCUTOFF) if (widthDiff > WIDTHCUTOFF)
{ {
fontSizeChange = Math.Min((double)Math.Max((double)Math.Floor(WIDTHTOFONTSCALAR * widthDiff) - WIDTHTOFONTOFFSET, INCREMENTOFFSET), MAXFONTINCREMENT); fontSizeChange = Math.Min(Math.Max(Math.Floor(WIDTHTOFONTSCALAR * widthDiff) - WIDTHTOFONTOFFSET, INCREMENTOFFSET), MAXFONTINCREMENT);
} }
if (m_textBlock.ActualWidth < containerSize && Math.Abs(m_textBlock.FontSize - MaxFontSize) > FONTTOLERANCE && !m_haveCalculatedMax) if (m_textBlock.ActualWidth < containerSize && Math.Abs(m_textBlock.FontSize - MaxFontSize) > FONTTOLERANCE && !m_haveCalculatedMax)
{ {

View file

@ -33,11 +33,11 @@ namespace CalculatorApp
// Using a DependencyProperty as the backing store for ButtonId. This enables animation, styling, binding, etc... // Using a DependencyProperty as the backing store for ButtonId. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ButtonIdProperty = public static readonly DependencyProperty ButtonIdProperty =
DependencyProperty.Register(nameof(ButtonId), typeof(NumbersAndOperatorsEnum), typeof(CalculatorButton), new PropertyMetadata(default(NumbersAndOperatorsEnum), new PropertyChangedCallback((sender, args) => DependencyProperty.Register(nameof(ButtonId), typeof(NumbersAndOperatorsEnum), typeof(CalculatorButton), new PropertyMetadata(default(NumbersAndOperatorsEnum), (sender, args) =>
{ {
var self = (CalculatorButton)sender; var self = (CalculatorButton)sender;
self.OnButtonIdPropertyChanged((NumbersAndOperatorsEnum)args.OldValue, (NumbersAndOperatorsEnum)args.NewValue); self.OnButtonIdPropertyChanged((NumbersAndOperatorsEnum)args.OldValue, (NumbersAndOperatorsEnum)args.NewValue);
}))); }));
public string AuditoryFeedback public string AuditoryFeedback
{ {
@ -47,11 +47,11 @@ namespace CalculatorApp
// Using a DependencyProperty as the backing store for AuditoryFeedback. This enables animation, styling, binding, etc... // Using a DependencyProperty as the backing store for AuditoryFeedback. This enables animation, styling, binding, etc...
public static readonly DependencyProperty AuditoryFeedbackProperty = public static readonly DependencyProperty AuditoryFeedbackProperty =
DependencyProperty.Register(nameof(AuditoryFeedback), typeof(string), typeof(CalculatorButton), new PropertyMetadata(string.Empty, new PropertyChangedCallback((sender, args) => DependencyProperty.Register(nameof(AuditoryFeedback), typeof(string), typeof(CalculatorButton), new PropertyMetadata(string.Empty, (sender, args) =>
{ {
var self = (CalculatorButton)sender; var self = (CalculatorButton)sender;
self.OnAuditoryFeedbackPropertyChanged((string)args.OldValue, (string)args.NewValue); self.OnAuditoryFeedbackPropertyChanged((string)args.OldValue, (string)args.NewValue);
}))); }));
public Windows.UI.Xaml.Media.Brush HoverBackground public Windows.UI.Xaml.Media.Brush HoverBackground
{ {

View file

@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved. // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. // Licensed under the MIT License.
using CalculatorApp.ViewModel.Common; using CalculatorApp.ViewModel.Common;
@ -16,10 +16,6 @@ namespace CalculatorApp
{ {
public sealed class EquationTextBox : Windows.UI.Xaml.Controls.Control public sealed class EquationTextBox : Windows.UI.Xaml.Controls.Control
{ {
public EquationTextBox()
{
}
public Windows.UI.Xaml.Media.SolidColorBrush EquationColor public Windows.UI.Xaml.Media.SolidColorBrush EquationColor
{ {
get => (Windows.UI.Xaml.Media.SolidColorBrush)GetValue(EquationColorProperty); get => (Windows.UI.Xaml.Media.SolidColorBrush)GetValue(EquationColorProperty);

View file

@ -10,10 +10,6 @@ namespace CalculatorApp
{ {
public sealed class OperatorPanelButton : Windows.UI.Xaml.Controls.Primitives.ToggleButton public sealed class OperatorPanelButton : Windows.UI.Xaml.Controls.Primitives.ToggleButton
{ {
public OperatorPanelButton()
{
}
public string Text public string Text
{ {
get => (string)GetValue(TextProperty); get => (string)GetValue(TextProperty);

View file

@ -12,10 +12,6 @@ namespace CalculatorApp
{ {
public sealed class OperatorPanelListView : Windows.UI.Xaml.Controls.ListView public sealed class OperatorPanelListView : Windows.UI.Xaml.Controls.ListView
{ {
public OperatorPanelListView()
{
}
protected override void OnApplyTemplate() protected override void OnApplyTemplate()
{ {
m_scrollViewer = GetTemplateChild("ScrollViewer") as ScrollViewer; m_scrollViewer = GetTemplateChild("ScrollViewer") as ScrollViewer;

View file

@ -37,11 +37,11 @@ namespace CalculatorApp
// Using a DependencyProperty as the backing store for TokensUpdated. This enables animation, styling, binding, etc... // Using a DependencyProperty as the backing store for TokensUpdated. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TokensUpdatedProperty = public static readonly DependencyProperty TokensUpdatedProperty =
DependencyProperty.Register(nameof(TokensUpdated), typeof(bool), typeof(OverflowTextBlock), new PropertyMetadata(default(bool), new PropertyChangedCallback((sender, args) => DependencyProperty.Register(nameof(TokensUpdated), typeof(bool), typeof(OverflowTextBlock), new PropertyMetadata(default(bool), (sender, args) =>
{ {
var self = (OverflowTextBlock)sender; var self = (OverflowTextBlock)sender;
self.OnTokensUpdatedPropertyChanged((bool)args.OldValue, (bool)args.NewValue); self.OnTokensUpdatedPropertyChanged((bool)args.OldValue, (bool)args.NewValue);
}))); }));
public OverflowButtonPlacement ScrollButtonsPlacement public OverflowButtonPlacement ScrollButtonsPlacement
{ {
@ -51,11 +51,11 @@ namespace CalculatorApp
// Using a DependencyProperty as the backing store for ScrollButtonsPlacement. This enables animation, styling, binding, etc... // Using a DependencyProperty as the backing store for ScrollButtonsPlacement. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ScrollButtonsPlacementProperty = public static readonly DependencyProperty ScrollButtonsPlacementProperty =
DependencyProperty.Register(nameof(ScrollButtonsPlacement), typeof(OverflowButtonPlacement), typeof(OverflowTextBlock), new PropertyMetadata(default(OverflowButtonPlacement), new PropertyChangedCallback((sender, args) => DependencyProperty.Register(nameof(ScrollButtonsPlacement), typeof(OverflowButtonPlacement), typeof(OverflowTextBlock), new PropertyMetadata(default(OverflowButtonPlacement), (sender, args) =>
{ {
var self = (OverflowTextBlock)sender; var self = (OverflowTextBlock)sender;
self.OnScrollButtonsPlacementPropertyChanged((OverflowButtonPlacement)args.OldValue, (OverflowButtonPlacement)args.NewValue); self.OnScrollButtonsPlacementPropertyChanged((OverflowButtonPlacement)args.OldValue, (OverflowButtonPlacement)args.NewValue);
}))); }));
public bool IsActive public bool IsActive
{ {

View file

@ -9,9 +9,6 @@ namespace CalculatorApp
{ {
public sealed class RadixButton : Windows.UI.Xaml.Controls.RadioButton public sealed class RadixButton : Windows.UI.Xaml.Controls.RadioButton
{ {
public RadixButton()
{ }
internal string GetRawDisplayValue() internal string GetRawDisplayValue()
{ {
string radixContent = Content?.ToString(); string radixContent = Content?.ToString();

View file

@ -16,10 +16,6 @@ namespace CalculatorApp
{ {
public sealed class SupplementaryItemsControl : ItemsControl public sealed class SupplementaryItemsControl : ItemsControl
{ {
public SupplementaryItemsControl()
{
}
protected override DependencyObject GetContainerForItemOverride() protected override DependencyObject GetContainerForItemOverride()
{ {
return new SupplementaryContentPresenter(); return new SupplementaryContentPresenter();
@ -38,10 +34,6 @@ namespace CalculatorApp
public sealed class SupplementaryContentPresenter : ContentPresenter public sealed class SupplementaryContentPresenter : ContentPresenter
{ {
public SupplementaryContentPresenter()
{
}
protected override AutomationPeer OnCreateAutomationPeer() protected override AutomationPeer OnCreateAutomationPeer()
{ {
return new SupplementaryContentPresenterAP(this); return new SupplementaryContentPresenterAP(this);

View file

@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved. // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. // Licensed under the MIT License.
using CalculatorApp.ViewModel.Common; using CalculatorApp.ViewModel.Common;
@ -16,8 +16,7 @@ namespace CalculatorApp
{ {
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{ {
DisplayExpressionToken token = (item as DisplayExpressionToken); if (item is DisplayExpressionToken token)
if (token != null)
{ {
CalculatorApp.ViewModel.Common.TokenType type = token.Type; CalculatorApp.ViewModel.Common.TokenType type = token.Type;

View file

@ -42,8 +42,6 @@ namespace CalculatorApp
convertedValue = resourceLoader.GetResourceString("Hex"); convertedValue = resourceLoader.GetResourceString("Hex");
break; break;
} }
default:
break;
} }
return convertedValue; return convertedValue;

View file

@ -11,10 +11,6 @@ namespace CalculatorApp
{ {
public sealed class KeyGraphFeaturesTemplateSelector : Windows.UI.Xaml.Controls.DataTemplateSelector public sealed class KeyGraphFeaturesTemplateSelector : Windows.UI.Xaml.Controls.DataTemplateSelector
{ {
public KeyGraphFeaturesTemplateSelector()
{
}
public Windows.UI.Xaml.DataTemplate RichEditTemplate { get; set; } public Windows.UI.Xaml.DataTemplate RichEditTemplate { get; set; }
public Windows.UI.Xaml.DataTemplate GridTemplate { get; set; } public Windows.UI.Xaml.DataTemplate GridTemplate { get; set; }
public Windows.UI.Xaml.DataTemplate TextBlockTemplate { get; set; } public Windows.UI.Xaml.DataTemplate TextBlockTemplate { get; set; }

View file

@ -79,7 +79,7 @@ namespace CalculatorApp.Utils
if (callbackToken.RootFrame.IsAlive) if (callbackToken.RootFrame.IsAlive)
{ {
Frame rootFrame = callbackToken.RootFrame.Target as Frame; Frame rootFrame = callbackToken.RootFrame.Target as Frame;
rootFrame.UnregisterPropertyChangedCallback(Frame.RequestedThemeProperty, callbackToken.Token); rootFrame.UnregisterPropertyChangedCallback(FrameworkElement.RequestedThemeProperty, callbackToken.Token);
} }
} }
} }

View file

@ -225,7 +225,7 @@ namespace CalculatorApp
string memoryPaneName = AppResourceProvider.GetInstance().GetResourceString("MemoryPane"); string memoryPaneName = AppResourceProvider.GetInstance().GetResourceString("MemoryPane");
MemoryFlyout.FlyoutPresenterStyle.Setters.Add(new Setter(AutomationProperties.NameProperty, memoryPaneName)); MemoryFlyout.FlyoutPresenterStyle.Setters.Add(new Setter(AutomationProperties.NameProperty, memoryPaneName));
if (Windows.Foundation.Metadata.ApiInformation.IsEventPresent("Windows.UI.Xaml.Controls.Primitives.FlyoutBase", "Closing")) if (Windows.Foundation.Metadata.ApiInformation.IsEventPresent("Windows.UI.Xaml.Controls.Primitives.FlyoutBase", nameof(FlyoutBase.Closing)))
{ {
HistoryFlyout.Closing += HistoryFlyout_Closing; HistoryFlyout.Closing += HistoryFlyout_Closing;
MemoryFlyout.Closing += OnMemoryFlyoutClosing; MemoryFlyout.Closing += OnMemoryFlyoutClosing;
@ -234,7 +234,7 @@ namespace CalculatorApp
// Delay load things later when we get a chance. // Delay load things later when we get a chance.
WeakReference weakThis = new WeakReference(this); WeakReference weakThis = new WeakReference(this);
_ = this.Dispatcher.RunAsync( _ = this.Dispatcher.RunAsync(
CoreDispatcherPriority.Normal, new DispatchedHandler(() => CoreDispatcherPriority.Normal, () =>
{ {
if (TraceLogger.GetInstance().IsWindowIdInLog(ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread()))) if (TraceLogger.GetInstance().IsWindowIdInLog(ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread())))
{ {
@ -243,7 +243,7 @@ namespace CalculatorApp
refThis.GetMemory(); refThis.GetMemory();
} }
} }
})); });
} }
private void LoadResourceStrings() private void LoadResourceStrings()

View file

@ -36,7 +36,7 @@ namespace CalculatorApp
{ {
get get
{ {
Debug.Assert(DataContext as ViewModel.StandardCalculatorViewModel != null, "static_cast result must NOT be null"); Debug.Assert(DataContext is ViewModel.StandardCalculatorViewModel, "static_cast result must NOT be null");
return DataContext as ViewModel.StandardCalculatorViewModel; return DataContext as ViewModel.StandardCalculatorViewModel;
} }
} }

View file

@ -58,37 +58,25 @@ namespace CalculatorApp
private void DecButtonChecked(object sender, RoutedEventArgs e) private void DecButtonChecked(object sender, RoutedEventArgs e)
{ {
TraceLogger.GetInstance().UpdateButtonUsage(NumbersAndOperatorsEnum.DecButton, ViewMode.Programmer); TraceLogger.GetInstance().UpdateButtonUsage(NumbersAndOperatorsEnum.DecButton, ViewMode.Programmer);
if (Model != null) Model?.SwitchProgrammerModeBase(NumberBase.DecBase);
{
Model.SwitchProgrammerModeBase(NumberBase.DecBase);
}
} }
private void HexButtonChecked(object sender, RoutedEventArgs e) private void HexButtonChecked(object sender, RoutedEventArgs e)
{ {
TraceLogger.GetInstance().UpdateButtonUsage(NumbersAndOperatorsEnum.HexButton, ViewMode.Programmer); TraceLogger.GetInstance().UpdateButtonUsage(NumbersAndOperatorsEnum.HexButton, ViewMode.Programmer);
if (Model != null) Model?.SwitchProgrammerModeBase(NumberBase.HexBase);
{
Model.SwitchProgrammerModeBase(NumberBase.HexBase);
}
} }
private void BinButtonChecked(object sender, RoutedEventArgs e) private void BinButtonChecked(object sender, RoutedEventArgs e)
{ {
TraceLogger.GetInstance().UpdateButtonUsage(NumbersAndOperatorsEnum.BinButton, ViewMode.Programmer); TraceLogger.GetInstance().UpdateButtonUsage(NumbersAndOperatorsEnum.BinButton, ViewMode.Programmer);
if (Model != null) Model?.SwitchProgrammerModeBase(NumberBase.BinBase);
{
Model.SwitchProgrammerModeBase(NumberBase.BinBase);
}
} }
private void OctButtonChecked(object sender, RoutedEventArgs e) private void OctButtonChecked(object sender, RoutedEventArgs e)
{ {
TraceLogger.GetInstance().UpdateButtonUsage(NumbersAndOperatorsEnum.OctButton, ViewMode.Programmer); TraceLogger.GetInstance().UpdateButtonUsage(NumbersAndOperatorsEnum.OctButton, ViewMode.Programmer);
if (Model != null) Model?.SwitchProgrammerModeBase(NumberBase.OctBase);
{
Model.SwitchProgrammerModeBase(NumberBase.OctBase);
}
} }
private void OnCopyMenuItemClicked(object sender, RoutedEventArgs e) private void OnCopyMenuItemClicked(object sender, RoutedEventArgs e)

View file

@ -38,8 +38,8 @@ namespace CalculatorApp
m_accessibilitySettings.HighContrastChanged += OnHighContrastChanged; m_accessibilitySettings.HighContrastChanged += OnHighContrastChanged;
m_isHighContrast = m_accessibilitySettings.HighContrast; m_isHighContrast = m_accessibilitySettings.HighContrast;
m_uiSettings = new UISettings(); var mUiSettings = new UISettings();
m_uiSettings.ColorValuesChanged += OnColorValuesChanged; mUiSettings.ColorValuesChanged += OnColorValuesChanged;
ReloadAvailableColors(m_accessibilitySettings.HighContrast, true); ReloadAvailableColors(m_accessibilitySettings.HighContrast, true);
@ -258,8 +258,7 @@ namespace CalculatorApp
} }
if (submission.Source == EquationSubmissionSource.ENTER_KEY if (submission.Source == EquationSubmissionSource.ENTER_KEY
|| (submission.Source == EquationSubmissionSource.FOCUS_LOST && submission.HasTextChanged && eq.Expression != null || (submission.Source == EquationSubmissionSource.FOCUS_LOST && submission.HasTextChanged && !string.IsNullOrEmpty(eq.Expression)))
&& eq.Expression.Length > 0))
{ {
if (submission.Source == EquationSubmissionSource.ENTER_KEY) if (submission.Source == EquationSubmissionSource.ENTER_KEY)
{ {
@ -355,13 +354,13 @@ namespace CalculatorApp
{ {
WeakReference weakThis = new WeakReference(this); WeakReference weakThis = new WeakReference(this);
_ = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => _ = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{ {
if (weakThis.Target is EquationInputArea refThis && refThis.m_isHighContrast == refThis.m_accessibilitySettings.HighContrast) if (weakThis.Target is EquationInputArea refThis && refThis.m_isHighContrast == refThis.m_accessibilitySettings.HighContrast)
{ {
refThis.ReloadAvailableColors(false, false); refThis.ReloadAvailableColors(false, false);
} }
})); });
} }
private void EquationTextBox_RemoveButtonClicked(object sender, RoutedEventArgs e) private void EquationTextBox_RemoveButtonClicked(object sender, RoutedEventArgs e)
@ -436,10 +435,7 @@ namespace CalculatorApp
if (index >= 0) if (index >= 0)
{ {
var container = (UIElement)EquationInputList.ContainerFromIndex(index); var container = (UIElement)EquationInputList.ContainerFromIndex(index);
if (container != null) container?.StartBringIntoView();
{
container.StartBringIntoView();
}
} }
} }
} }
@ -466,10 +462,7 @@ namespace CalculatorApp
if (index >= 0) if (index >= 0)
{ {
var container = (UIElement)EquationInputList.ContainerFromIndex(index); var container = (UIElement)EquationInputList.ContainerFromIndex(index);
if (container != null) container?.StartBringIntoView();
{
container.StartBringIntoView();
}
} }
} }
} }
@ -594,11 +587,11 @@ namespace CalculatorApp
{ {
TimeSpan timeSpan = new TimeSpan(10000000); // 1 tick = 100 nanoseconds, and 10000000 ticks = 1 second. TimeSpan timeSpan = new TimeSpan(10000000); // 1 tick = 100 nanoseconds, and 10000000 ticks = 1 second.
DispatcherTimerDelayer delayer = new DispatcherTimerDelayer(timeSpan); DispatcherTimerDelayer delayer = new DispatcherTimerDelayer(timeSpan);
delayer.Action += new EventHandler<object>((object s, object arg) => delayer.Action += (object s, object arg) =>
{ {
CalculatorApp.ViewModel.Common.TraceLogger.GetInstance().LogVariableChanged("Slider", name); CalculatorApp.ViewModel.Common.TraceLogger.GetInstance().LogVariableChanged("Slider", name);
variableSliders.Remove(name); variableSliders.Remove(name);
}); };
delayer.Start(); delayer.Start();
variableSliders.Add(name, delayer); variableSliders.Add(name, delayer);
} }
@ -612,12 +605,8 @@ namespace CalculatorApp
private EquationViewModel GetViewModelFromEquationTextBox(object sender) private EquationViewModel GetViewModelFromEquationTextBox(object sender)
{ {
var tb = (EquationTextBox)sender; var tb = (EquationTextBox)sender;
if (tb == null)
{
return null;
}
var eq = (EquationViewModel)tb.DataContext; var eq = (EquationViewModel)tb?.DataContext;
return eq; return eq;
} }
@ -643,7 +632,6 @@ namespace CalculatorApp
private const string IsMatchAppThemePropertyName = "IsMatchAppTheme"; private const string IsMatchAppThemePropertyName = "IsMatchAppTheme";
private readonly Windows.UI.ViewManagement.AccessibilitySettings m_accessibilitySettings; private readonly Windows.UI.ViewManagement.AccessibilitySettings m_accessibilitySettings;
private readonly Windows.UI.ViewManagement.UISettings m_uiSettings;
private int m_lastLineColorIndex; private int m_lastLineColorIndex;
private int m_lastFunctionLabelIndex; private int m_lastFunctionLabelIndex;
private bool m_isHighContrast; private bool m_isHighContrast;

View file

@ -230,14 +230,7 @@ namespace CalculatorApp
if (e.AddedItems.Count > 0) if (e.AddedItems.Count > 0)
{ {
var brush = (e.AddedItems[0] as SolidColorBrush); var brush = (e.AddedItems[0] as SolidColorBrush);
if (brush == null) SelectedColor = brush?.Color ?? Colors.Black;
{
SelectedColor = Colors.Black;
}
else
{
SelectedColor = brush.Color;
}
CalculatorApp.ViewModel.Common.TraceLogger.GetInstance().LogGraphLineStyleChanged(LineStyleType.Color); CalculatorApp.ViewModel.Common.TraceLogger.GetInstance().LogGraphLineStyleChanged(LineStyleType.Color);
} }
@ -293,9 +286,8 @@ namespace CalculatorApp
foreach (var item in StyleChooserBox.Items) foreach (var item in StyleChooserBox.Items)
{ {
var style = ((EquationLineStyle)item); var style = ((EquationLineStyle)item);
var comboBoxItem = (StyleChooserBox.ContainerFromItem(style) as ComboBoxItem);
if (comboBoxItem == null) if (!(StyleChooserBox.ContainerFromItem(style) is ComboBoxItem comboBoxItem))
{ {
continue; continue;
} }

View file

@ -75,8 +75,8 @@ namespace CalculatorApp
m_accessibilitySettings.HighContrastChanged += OnHighContrastChanged; m_accessibilitySettings.HighContrastChanged += OnHighContrastChanged;
m_uiSettings = new UISettings(); var mUiSettings = new UISettings();
m_uiSettings.ColorValuesChanged += OnColorValuesChanged; mUiSettings.ColorValuesChanged += OnColorValuesChanged;
ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
@ -376,10 +376,7 @@ namespace CalculatorApp
var peer = FrameworkElementAutomationPeer.FromElement(TraceValue); var peer = FrameworkElementAutomationPeer.FromElement(TraceValue);
if (peer != null) peer?.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
{
peer.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
}
PositionGraphPopup(); PositionGraphPopup();
} }
@ -402,19 +399,16 @@ namespace CalculatorApp
try try
{ {
string rawHtml; var rawHtml = "<p><img src='graph.png' width='600' alt='" + resourceLoader.GetString("GraphImageAltText") + "'></p>";
string equationHtml;
rawHtml = "<p><img src='graph.png' width='600' alt='" + resourceLoader.GetString("GraphImageAltText") + "'></p>";
var equations = ViewModel.Equations; var equations = ViewModel.Equations;
bool hasEquations = false; bool hasEquations = false;
if (equations.Count > 0) if (equations.Count > 0)
{ {
equationHtml = "<span style=\"color: rgb(68, 114, 196); font-style: bold; font-size : 13pt;\">" var equationHtml = "<span style=\"color: rgb(68, 114, 196); font-style: bold; font-size : 13pt;\">"
+ resourceLoader.GetString("EquationsShareHeader") + "</span>" + resourceLoader.GetString("EquationsShareHeader") + "</span>"
+ "<table cellpadding=\"0\" cellspacing=\"0\" >"; + "<table cellpadding=\"0\" cellspacing=\"0\" >";
foreach (var equation in equations) foreach (var equation in equations)
{ {
@ -429,8 +423,7 @@ namespace CalculatorApp
expression = GraphingControl.ConvertToLinear(expression); expression = GraphingControl.ConvertToLinear(expression);
string equationColorHtml; var equationColorHtml = "color:rgb(" + color.R.ToString() + "," + color.G.ToString() + "," + color.B.ToString() + ");";
equationColorHtml = "color:rgb(" + color.R.ToString() + "," + color.G.ToString() + "," + color.B.ToString() + ");";
equationHtml += "<tr style=\"margin: 0pt 0pt 0pt 0pt; padding: 0pt 0pt 0pt 0pt; \"><td><span style=\"font-size: 22pt; line-height: 0;" equationHtml += "<tr style=\"margin: 0pt 0pt 0pt 0pt; padding: 0pt 0pt 0pt 0pt; \"><td><span style=\"font-size: 22pt; line-height: 0;"
+ equationColorHtml + "\">&#x25A0;</span></td><td><div style=\"margin: 4pt 0pt 0pt 6pt;\">" + equationColorHtml + "\">&#x25A0;</span></td><td><div style=\"margin: 4pt 0pt 0pt 6pt;\">"
@ -518,7 +511,7 @@ namespace CalculatorApp
private void GraphingControl_LosingFocus(UIElement sender, LosingFocusEventArgs args) private void GraphingControl_LosingFocus(UIElement sender, LosingFocusEventArgs args)
{ {
if (!(args.NewFocusedElement is FrameworkElement newFocusElement) || newFocusElement.Name == null) if (!(args.NewFocusedElement is FrameworkElement))
{ {
// Because clicking on the swap chain panel will try to move focus to a control that can't actually take focus // Because clicking on the swap chain panel will try to move focus to a control that can't actually take focus
// we will get a null destination. So we are going to try and cancel that request. // we will get a null destination. So we are going to try and cancel that request.
@ -534,23 +527,13 @@ namespace CalculatorApp
private void GraphingControl_GraphViewChangedEvent(object sender, GraphViewChangedReason reason) private void GraphingControl_GraphViewChangedEvent(object sender, GraphViewChangedReason reason)
{ {
if (reason == GraphViewChangedReason.Manipulation) IsManualAdjustment = reason == GraphViewChangedReason.Manipulation;
{
IsManualAdjustment = true;
}
else
{
IsManualAdjustment = false;
}
UpdateGraphAutomationName(); UpdateGraphAutomationName();
var announcement = CalculatorAnnouncement.GetGraphViewChangedAnnouncement(GraphControlAutomationName); var announcement = CalculatorAnnouncement.GetGraphViewChangedAnnouncement(GraphControlAutomationName);
var peer = FrameworkElementAutomationPeer.FromElement(GraphingControl); var peer = FrameworkElementAutomationPeer.FromElement(GraphingControl);
if (peer != null) peer?.RaiseNotificationEvent(announcement.Kind, announcement.Processing, announcement.Announcement, announcement.ActivityId);
{
peer.RaiseNotificationEvent(announcement.Kind, announcement.Processing, announcement.Announcement, announcement.ActivityId);
}
} }
private void GraphingControl_GraphPlottedEvent(object sender, RoutedEventArgs e) private void GraphingControl_GraphPlottedEvent(object sender, RoutedEventArgs e)
@ -752,13 +735,13 @@ namespace CalculatorApp
private void OnColorValuesChanged(UISettings sender, object args) private void OnColorValuesChanged(UISettings sender, object args)
{ {
WeakReference weakThis = new WeakReference(this); WeakReference weakThis = new WeakReference(this);
_ = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => _ = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{ {
if (weakThis.Target is GraphingCalculator refThis && IsMatchAppTheme) if (weakThis.Target is GraphingCalculator refThis && IsMatchAppTheme)
{ {
refThis.UpdateGraphTheme(); refThis.UpdateGraphTheme();
} }
})); });
} }
private void UpdateGraphTheme() private void UpdateGraphTheme()
@ -788,13 +771,13 @@ namespace CalculatorApp
IsMatchAppTheme = isMatchAppTheme; IsMatchAppTheme = isMatchAppTheme;
WeakReference weakThis = new WeakReference(this); WeakReference weakThis = new WeakReference(this);
_ = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => _ = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{ {
if (weakThis.Target is GraphingCalculator refThis) if (weakThis.Target is GraphingCalculator refThis)
{ {
refThis.UpdateGraphTheme(); refThis.UpdateGraphTheme();
} }
})); });
} }
private const double zoomInScale = 1 / 1.0625; private const double zoomInScale = 1 / 1.0625;
@ -805,7 +788,6 @@ namespace CalculatorApp
private CalculatorApp.ViewModel.GraphingCalculatorViewModel m_viewModel; private CalculatorApp.ViewModel.GraphingCalculatorViewModel m_viewModel;
private readonly Windows.UI.ViewManagement.AccessibilitySettings m_accessibilitySettings; private readonly Windows.UI.ViewManagement.AccessibilitySettings m_accessibilitySettings;
private bool m_cursorShadowInitialized; private bool m_cursorShadowInitialized;
private readonly Windows.UI.ViewManagement.UISettings m_uiSettings;
private Windows.UI.Xaml.Controls.Flyout m_graphFlyout; private Windows.UI.Xaml.Controls.Flyout m_graphFlyout;
private CalculatorApp.GraphingSettings m_graphSettings; private CalculatorApp.GraphingSettings m_graphSettings;

View file

@ -103,11 +103,11 @@ namespace CalculatorApp
{ {
InverseHyperbolicTrigFunctions.Visibility = Visibility.Visible; InverseHyperbolicTrigFunctions.Visibility = Visibility.Visible;
} }
else if (isShiftChecked && !isHypeChecked) else if (isShiftChecked)
{ {
InverseTrigFunctions.Visibility = Visibility.Visible; InverseTrigFunctions.Visibility = Visibility.Visible;
} }
else if (!isShiftChecked && isHypeChecked) else if (isHypeChecked)
{ {
HyperbolicTrigFunctions.Visibility = Visibility.Visible; HyperbolicTrigFunctions.Visibility = Visibility.Visible;
} }

View file

@ -25,7 +25,7 @@ namespace CalculatorApp
InitializeComponent(); InitializeComponent();
} }
public CalculatorApp.ViewModel.GraphingSettingsViewModel ViewModel { get; set; } public CalculatorApp.ViewModel.GraphingSettingsViewModel ViewModel { get; }
public bool IsMatchAppTheme public bool IsMatchAppTheme
{ {

View file

@ -48,11 +48,8 @@ namespace CalculatorApp
private void ListView_ItemClick(object sender, ItemClickEventArgs e) private void ListView_ItemClick(object sender, ItemClickEventArgs e)
{ {
HistoryViewModel historyVM = (DataContext as HistoryViewModel);
HistoryItemViewModel clickedItem = (e.ClickedItem as HistoryItemViewModel);
// When the user clears the history list in the overlay view and presses enter, the clickedItem is nullptr // When the user clears the history list in the overlay view and presses enter, the clickedItem is nullptr
if (clickedItem != null && historyVM != null) if (e.ClickedItem is HistoryItemViewModel clickedItem && DataContext is HistoryViewModel historyVM)
{ {
historyVM.ShowItem(clickedItem); historyVM.ShowItem(clickedItem);
} }
@ -60,8 +57,7 @@ namespace CalculatorApp
private void OnCopyMenuItemClicked(object sender, RoutedEventArgs e) private void OnCopyMenuItemClicked(object sender, RoutedEventArgs e)
{ {
var listViewItem = HistoryContextMenu.Target; var listViewItem = HistoryContextMenu.Target;
var itemViewModel = (HistoryListView.ItemFromContainer(listViewItem) as HistoryItemViewModel); if (HistoryListView.ItemFromContainer(listViewItem) is HistoryItemViewModel itemViewModel)
if (itemViewModel != null)
{ {
CopyPasteManager.CopyToClipboard(itemViewModel.Result); CopyPasteManager.CopyToClipboard(itemViewModel.Result);
} }
@ -69,16 +65,14 @@ namespace CalculatorApp
private void OnDeleteMenuItemClicked(object sender, RoutedEventArgs e) private void OnDeleteMenuItemClicked(object sender, RoutedEventArgs e)
{ {
var listViewItem = HistoryContextMenu.Target; var listViewItem = HistoryContextMenu.Target;
var itemViewModel = (HistoryListView.ItemFromContainer(listViewItem) as HistoryItemViewModel); if (HistoryListView.ItemFromContainer(listViewItem) is HistoryItemViewModel itemViewModel)
if (itemViewModel != null)
{ {
Model.DeleteItem(itemViewModel); Model.DeleteItem(itemViewModel);
} }
} }
private void OnDeleteSwipeInvoked(MUXC.SwipeItem sender, MUXC.SwipeItemInvokedEventArgs e) private void OnDeleteSwipeInvoked(MUXC.SwipeItem sender, MUXC.SwipeItemInvokedEventArgs e)
{ {
var swipedItem = (e.SwipeControl.DataContext as HistoryItemViewModel); if (e.SwipeControl.DataContext is HistoryItemViewModel swipedItem)
if (swipedItem != null)
{ {
Model.DeleteItem(swipedItem); Model.DeleteItem(swipedItem);
} }

View file

@ -66,10 +66,7 @@ namespace CalculatorApp
Window.Current.SizeChanged -= WindowSizeChanged; Window.Current.SizeChanged -= WindowSizeChanged;
m_accessibilitySettings.HighContrastChanged -= OnHighContrastChanged; m_accessibilitySettings.HighContrastChanged -= OnHighContrastChanged;
if (m_calculator != null) m_calculator?.UnregisterEventHandlers();
{
m_calculator.UnregisterEventHandlers();
}
} }
public void SetDefaultFocus() public void SetDefaultFocus()
@ -368,8 +365,7 @@ namespace CalculatorApp
return; return;
} }
var item = (e.SelectedItemContainer as MUXC.NavigationViewItem); if (e.SelectedItemContainer is MUXC.NavigationViewItem item)
if (item != null)
{ {
Model.Mode = (ViewMode)item.Tag; Model.Mode = (ViewMode)item.Tag;
} }
@ -435,10 +431,7 @@ namespace CalculatorApp
private void UpdatePanelViewState() private void UpdatePanelViewState()
{ {
if (m_calculator != null) m_calculator?.UpdatePanelViewState();
{
m_calculator.UpdatePanelViewState();
}
} }
private void OnHighContrastChanged(AccessibilitySettings sender, object args) private void OnHighContrastChanged(AccessibilitySettings sender, object args)
@ -468,14 +461,14 @@ namespace CalculatorApp
// Delay load things later when we get a chance. // Delay load things later when we get a chance.
_ = Dispatcher.RunAsync( _ = Dispatcher.RunAsync(
CoreDispatcherPriority.Normal, new DispatchedHandler(() => CoreDispatcherPriority.Normal, () =>
{ {
if (TraceLogger.GetInstance().IsWindowIdInLog(ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread()))) if (TraceLogger.GetInstance().IsWindowIdInLog(ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread())))
{ {
AppLifecycleLogger.GetInstance().LaunchUIResponsive(); AppLifecycleLogger.GetInstance().LaunchUIResponsive();
AppLifecycleLogger.GetInstance().LaunchVisibleComplete(); AppLifecycleLogger.GetInstance().LaunchVisibleComplete();
} }
})); });
} }
private void App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) private void App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
@ -528,10 +521,7 @@ namespace CalculatorApp
ShowHideControls(Model.Mode); ShowHideControls(Model.Mode);
} }
if (m_dateCalculator != null) m_dateCalculator?.CloseCalendarFlyout();
{
m_dateCalculator.CloseCalendarFlyout();
}
} }
private void EnsureDateCalculator() private void EnsureDateCalculator()

View file

@ -60,28 +60,19 @@ namespace CalculatorApp
private void OnClearMenuItemClicked(object sender, RoutedEventArgs e) private void OnClearMenuItemClicked(object sender, RoutedEventArgs e)
{ {
var memoryItem = GetMemoryItemForCurrentFlyout(); var memoryItem = GetMemoryItemForCurrentFlyout();
if (memoryItem != null) memoryItem?.Clear();
{
memoryItem.Clear();
}
} }
private void OnMemoryAddMenuItemClicked(object sender, RoutedEventArgs e) private void OnMemoryAddMenuItemClicked(object sender, RoutedEventArgs e)
{ {
var memoryItem = GetMemoryItemForCurrentFlyout(); var memoryItem = GetMemoryItemForCurrentFlyout();
if (memoryItem != null) memoryItem?.MemoryAdd();
{
memoryItem.MemoryAdd();
}
} }
private void OnMemorySubtractMenuItemClicked(object sender, RoutedEventArgs e) private void OnMemorySubtractMenuItemClicked(object sender, RoutedEventArgs e)
{ {
var memoryItem = GetMemoryItemForCurrentFlyout(); var memoryItem = GetMemoryItemForCurrentFlyout();
if (memoryItem != null) memoryItem?.MemorySubtract();
{
memoryItem.MemorySubtract();
}
} }
private MemoryItemViewModel GetMemoryItemForCurrentFlyout() private MemoryItemViewModel GetMemoryItemForCurrentFlyout()

View file

@ -1,4 +1,4 @@
using CalculatorApp.ViewModel; using CalculatorApp.ViewModel;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -46,9 +46,6 @@ namespace CalculatorApp
public sealed class SupplementaryResultDataTemplateSelector : Windows.UI.Xaml.Controls.DataTemplateSelector public sealed class SupplementaryResultDataTemplateSelector : Windows.UI.Xaml.Controls.DataTemplateSelector
{ {
public SupplementaryResultDataTemplateSelector()
{ }
public Windows.UI.Xaml.DataTemplate RegularTemplate { get; set; } public Windows.UI.Xaml.DataTemplate RegularTemplate { get; set; }
public Windows.UI.Xaml.DataTemplate DelighterTemplate { get; set; } public Windows.UI.Xaml.DataTemplate DelighterTemplate { get; set; }

View file

@ -92,7 +92,7 @@ namespace CalculatorApp
{ {
if (Frame.RequestedThemeProperty == dp) if (Frame.RequestedThemeProperty == dp)
{ {
_ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => { SetTitleBarControlColors(); })); _ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, SetTitleBarControlColors);
} }
} }
@ -120,8 +120,8 @@ namespace CalculatorApp
return; return;
} }
double leftAddition = 0; double leftAddition;
double rightAddition = 0; double rightAddition;
if (FlowDirection == FlowDirection.LeftToRight) if (FlowDirection == FlowDirection.LeftToRight)
{ {
@ -140,18 +140,14 @@ namespace CalculatorApp
private void ColorValuesChanged(Windows.UI.ViewManagement.UISettings sender, object e) private void ColorValuesChanged(Windows.UI.ViewManagement.UISettings sender, object e)
{ {
_ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => { SetTitleBarControlColors(); })); _ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, SetTitleBarControlColors);
} }
private void SetTitleBarControlColors() private void SetTitleBarControlColors()
{ {
var applicationView = ApplicationView.GetForCurrentView(); var applicationView = ApplicationView.GetForCurrentView();
if (applicationView == null)
{
return;
}
var applicationTitleBar = applicationView.TitleBar; var applicationTitleBar = applicationView?.TitleBar;
if (applicationTitleBar == null) if (applicationTitleBar == null)
{ {
return; return;
@ -184,11 +180,11 @@ namespace CalculatorApp
private void OnHighContrastChanged(Windows.UI.ViewManagement.AccessibilitySettings sender, object args) private void OnHighContrastChanged(Windows.UI.ViewManagement.AccessibilitySettings sender, object args)
{ {
_ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => _ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{ {
SetTitleBarControlColors(); SetTitleBarControlColors();
SetTitleBarVisibility(false); SetTitleBarVisibility(false);
})); });
} }
private void OnWindowActivated(object sender, WindowActivatedEventArgs e) private void OnWindowActivated(object sender, WindowActivatedEventArgs e)
@ -281,12 +277,12 @@ namespace CalculatorApp
public static readonly DependencyProperty BackButtonSpaceReservedProperty = public static readonly DependencyProperty BackButtonSpaceReservedProperty =
DependencyProperty.Register( DependencyProperty.Register(
nameof(BackButtonSpaceReserved), typeof(bool), typeof(TitleBar), nameof(BackButtonSpaceReserved), typeof(bool), typeof(TitleBar),
new PropertyMetadata(false, new PropertyChangedCallback((sender, args) => new PropertyMetadata(false, (sender, args) =>
{ {
var self = sender as TitleBar; var self = sender as TitleBar;
VisualStateManager.GoToState( VisualStateManager.GoToState(
self, (bool)args.NewValue ? self.BackButtonVisible.Name : self.BackButtonCollapsed.Name, true); self, (bool)args.NewValue ? self.BackButtonVisible.Name : self.BackButtonCollapsed.Name, true);
}))); }));
private readonly Windows.ApplicationModel.Core.CoreApplicationViewTitleBar m_coreTitleBar; private readonly Windows.ApplicationModel.Core.CoreApplicationViewTitleBar m_coreTitleBar;
private readonly Windows.UI.ViewManagement.UISettings m_uiSettings; private readonly Windows.UI.ViewManagement.UISettings m_uiSettings;

View file

@ -368,10 +368,7 @@ namespace CalculatorApp
private void HideProgressRing() private void HideProgressRing()
{ {
if (m_delayTimer != null) m_delayTimer?.Stop();
{
m_delayTimer.Stop();
}
CurrencyLoadingProgressRing.IsActive = false; CurrencyLoadingProgressRing.IsActive = false;
} }
@ -391,8 +388,8 @@ namespace CalculatorApp
private static readonly Lazy<UISettings> uiSettings = new Lazy<UISettings>(true); private static readonly Lazy<UISettings> uiSettings = new Lazy<UISettings>(true);
private readonly Windows.UI.Xaml.Controls.MenuFlyout m_resultsFlyout = default; private readonly Windows.UI.Xaml.Controls.MenuFlyout m_resultsFlyout = default;
private readonly string m_chargesMayApplyText = string.Empty; private readonly string m_chargesMayApplyText;
private readonly string m_failedToRefreshText = string.Empty; private readonly string m_failedToRefreshText;
private bool m_meteredConnectionOverride; private bool m_meteredConnectionOverride;

View file

@ -59,7 +59,7 @@ namespace CalculatorApp
public Task HandleViewRelease() public Task HandleViewRelease()
{ {
TaskCompletionSource<object> tsource = new TaskCompletionSource<object>(); TaskCompletionSource<object> tsource = new TaskCompletionSource<object>();
_ = m_coreDispatcher.RunAsync(CoreDispatcherPriority.Low, new DispatchedHandler(() => _ = m_coreDispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
{ {
KeyboardShortcutManager.OnWindowClosed(this.m_viewId); KeyboardShortcutManager.OnWindowClosed(this.m_viewId);
Window.Current.Content = null; Window.Current.Content = null;
@ -70,7 +70,7 @@ namespace CalculatorApp
tsource.SetResult(new object()); tsource.SetResult(new object());
this.m_coreDispatcher.StopProcessEvents(); this.m_coreDispatcher.StopProcessEvents();
Window.Current.Close(); Window.Current.Close();
})); });
return tsource.Task; return tsource.Task;
} }

View file

@ -17,12 +17,12 @@ namespace CalculatorUITestFramework
public string GetValue() public string GetValue()
{ {
var equalSignIndex = Item.Text.IndexOf("="); var equalSignIndex = Item.Text.IndexOf("=");
return Item.Text.Substring(equalSignIndex + 1).Trim(); return Item.Text[(equalSignIndex + 1)..].Trim();
} }
public string GetExpression() public string GetExpression()
{ {
var equalSignIndex = Item.Text.IndexOf("="); var equalSignIndex = Item.Text.IndexOf("=");
return Item.Text.Substring(0, equalSignIndex + 1).Trim(); return Item.Text[..(equalSignIndex + 1)].Trim();
} }
} }
} }

View file

@ -41,63 +41,27 @@ namespace CalculatorUITestFramework
/// <param name="mode">The mode to be changed to</param> /// <param name="mode">The mode to be changed to</param>
public void ChangeCalculatorMode(CalculatorMode mode) public void ChangeCalculatorMode(CalculatorMode mode)
{ {
string modeAccessibilityId; string modeAccessibilityId = mode switch
switch (mode)
{ {
case CalculatorMode.StandardCalculator: CalculatorMode.StandardCalculator => "Standard",
modeAccessibilityId = "Standard"; CalculatorMode.ScientificCalculator => "Scientific",
break; CalculatorMode.ProgrammerCalculator => "Programmer",
case CalculatorMode.ScientificCalculator: CalculatorMode.DateCalculator => "Date",
modeAccessibilityId = "Scientific"; CalculatorMode.Currency => "Currency",
break; CalculatorMode.Volume => "Volume",
case CalculatorMode.ProgrammerCalculator: CalculatorMode.Length => "Length",
modeAccessibilityId = "Programmer"; CalculatorMode.Weight => "Weight",
break; CalculatorMode.Temperature => "Temperature",
case CalculatorMode.DateCalculator: CalculatorMode.Energy => "Energy",
modeAccessibilityId = "Date"; CalculatorMode.Area => "Area",
break; CalculatorMode.Speed => "Speed",
case CalculatorMode.Currency: CalculatorMode.Time => "Time",
modeAccessibilityId = "Currency"; CalculatorMode.Power => "Power",
break; CalculatorMode.Data => "Data",
case CalculatorMode.Volume: CalculatorMode.Pressure => "Pressure",
modeAccessibilityId = "Volume"; CalculatorMode.Angle => "Angle",
break; _ => throw (new ArgumentException("The mode is not valid"))
case CalculatorMode.Length: };
modeAccessibilityId = "Length";
break;
case CalculatorMode.Weight:
modeAccessibilityId = "Weight";
break;
case CalculatorMode.Temperature:
modeAccessibilityId = "Temperature";
break;
case CalculatorMode.Energy:
modeAccessibilityId = "Energy";
break;
case CalculatorMode.Area:
modeAccessibilityId = "Area";
break;
case CalculatorMode.Speed:
modeAccessibilityId = "Speed";
break;
case CalculatorMode.Time:
modeAccessibilityId = "Time";
break;
case CalculatorMode.Power:
modeAccessibilityId = "Power";
break;
case CalculatorMode.Data:
modeAccessibilityId = "Data";
break;
case CalculatorMode.Pressure:
modeAccessibilityId = "Pressure";
break;
case CalculatorMode.Angle:
modeAccessibilityId = "Angle";
break;
default:
throw (new ArgumentException("The mode is not valid"));
}
this.NavigationMenuButton.Click(); this.NavigationMenuButton.Click();
this.NavigationMenuPane.WaitForDisplayed(); this.NavigationMenuPane.WaitForDisplayed();

View file

@ -34,7 +34,7 @@ namespace CalculatorUITestFramework
string numberStr = number.ToString(CultureInfo.InvariantCulture); string numberStr = number.ToString(CultureInfo.InvariantCulture);
if (numberStr.StartsWith("-")) if (numberStr.StartsWith("-"))
{ {
numberStr = numberStr.Substring(1) + "-"; numberStr = numberStr[1..] + "-";
} }
foreach (char digit in numberStr) foreach (char digit in numberStr)
{ {
@ -77,7 +77,7 @@ namespace CalculatorUITestFramework
this.NegateButton.Click(); this.NegateButton.Click();
break; break;
default: default:
throw (new ArgumentException(string.Format("{0} is not valid", digit))); throw (new ArgumentException($"{digit} is not valid"));
} }
} }
} }

View file

@ -109,21 +109,13 @@ namespace CalculatorUITestFramework
public void SetAngleOperator(AngleOperatorState value) public void SetAngleOperator(AngleOperatorState value)
{ {
//set the desired string value for the button //set the desired string value for the button
string desiredId; string desiredId = value switch
switch (value)
{ {
case AngleOperatorState.Degrees: AngleOperatorState.Degrees => "degButton",
desiredId = "degButton"; AngleOperatorState.Gradians => "gradButton",
break; AngleOperatorState.Radians => "radButton",
case AngleOperatorState.Gradians: _ => throw new NotImplementedException()
desiredId = "gradButton"; };
break;
case AngleOperatorState.Radians:
desiredId = "radButton";
break;
default:
throw new NotImplementedException();
}
while (this.DegRadGradButton.GetAttribute("AutomationId") != desiredId) while (this.DegRadGradButton.GetAttribute("AutomationId") != desiredId)
{ {
this.DegRadGradButton.Click(); this.DegRadGradButton.Click();

View file

@ -16,18 +16,7 @@ namespace CalculatorUITestFramework
public MemoryPanel MemoryPanel = new MemoryPanel(); public MemoryPanel MemoryPanel = new MemoryPanel();
private const string defaultAppId = "Microsoft.WindowsCalculator.Dev_8wekyb3d8bbwe!App"; private const string defaultAppId = "Microsoft.WindowsCalculator.Dev_8wekyb3d8bbwe!App";
private static WinAppDriver instance = null; private static WinAppDriver instance = null;
public static WinAppDriver Instance public static WinAppDriver Instance => instance ??= new WinAppDriver();
{
get
{
if (instance == null)
{
instance = new WinAppDriver();
}
return instance;
}
}
public WindowsDriver<WindowsElement> CalculatorSession { get; private set; } public WindowsDriver<WindowsElement> CalculatorSession { get; private set; }

View file

@ -18,6 +18,7 @@ using System;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
namespace CalculatorUITestFramework namespace CalculatorUITestFramework
@ -143,11 +144,11 @@ namespace CalculatorUITestFramework
private bool Ping() private bool Ping()
{ {
bool pinged = false;
Uri status; Uri status;
Uri service = this.ServiceUrl; Uri service = this.ServiceUrl;
var httpClient = new HttpClient();
httpClient.Timeout = this.InitializationTimeout;
if (service.IsLoopback) if (service.IsLoopback)
{ {
status = new Uri("http://localhost:" + Convert.ToString(this.Port) + "/status"); status = new Uri("http://localhost:" + Convert.ToString(this.Port) + "/status");
@ -157,31 +158,8 @@ namespace CalculatorUITestFramework
status = new Uri(service + "/status"); status = new Uri(service + "/status");
} }
DateTime endTime = DateTime.Now.Add(this.InitializationTimeout); var httpResponse = httpClient.GetAsync(status);
while (!pinged & DateTime.Now < endTime) return httpResponse.Result.IsSuccessStatusCode;
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(status);
HttpWebResponse response = null;
try
{
using (response = (HttpWebResponse)request.GetResponse())
{
pinged = true;
}
}
catch (Exception)
{
pinged = false;
}
finally
{
if (response != null)
{
response.Close();
}
}
}
return pinged;
} }
} }
} }

View file

@ -39,16 +39,12 @@ namespace CalculatorUITestFramework
public WindowsDriverServiceBuilder WithFileInfo(FileInfo fileInfo) public WindowsDriverServiceBuilder WithFileInfo(FileInfo fileInfo)
{ {
this.FileInfo = fileInfo ?? throw new ArgumentNullException("FileInfo should not be NULL"); this.FileInfo = fileInfo ?? throw new ArgumentNullException("FileInfo should not be null");
return this; return this;
} }
public WindowsDriverServiceBuilder WithStartUpTimeOut(TimeSpan startUpTimeout) public WindowsDriverServiceBuilder WithStartUpTimeOut(TimeSpan startUpTimeout)
{ {
if (startUpTimeout == null)
{
throw new ArgumentNullException("A startup timeout should not be NULL");
}
this.StartUpTimeout = startUpTimeout; this.StartUpTimeout = startUpTimeout;
return this; return this;
} }