Merge branch 'master' into patch-5

This commit is contained in:
NaBian authored and GitHub committed 2021-06-23 21:31:02 +08:00
commit 275f9ce1cd
173 files changed
+2208 -1798

No files matched your search

@@ -26,8 +26,8 @@ namespace HandyControlDemo
GlobalShortcut.Init(new List<KeyBinding>
{
new KeyBinding(ViewModelLocator.Instance.Main.GlobalShortcutInfoCmd, Key.I, ModifierKeys.Control | ModifierKeys.Alt),
new KeyBinding(ViewModelLocator.Instance.Main.GlobalShortcutWarningCmd, Key.E, ModifierKeys.Control | ModifierKeys.Alt)
new(ViewModelLocator.Instance.Main.GlobalShortcutInfoCmd, Key.I, ModifierKeys.Control | ModifierKeys.Alt),
new(ViewModelLocator.Instance.Main.GlobalShortcutWarningCmd, Key.E, ModifierKeys.Control | ModifierKeys.Alt)
});
Dialog.SetToken(this, MessageToken.MainWindow);
@@ -517,7 +517,7 @@
<value>TextDialog</value>
</data>
<data name="PleaseWait" xml:space="preserve">
<value>Proszę czekać</value>
<value>Proszę czekać...</value>
</data>
<data name="GrowlDemo" xml:space="preserve">
<value>Growl demo</value>
@@ -792,4 +792,7 @@
<data name="Success" xml:space="preserve">
<value>Success</value>
</data>
<data name="Empty" xml:space="preserve">
<value>Empty</value>
</data>
</root>
@@ -8,7 +8,7 @@ namespace HandyControlDemo.Properties.Langs
{
public class LangProvider : INotifyPropertyChanged
{
internal static LangProvider Instance => ResourceHelper.GetResource<LangProvider>("DemoLangs");
internal static LangProvider Instance { get; } = ResourceHelper.GetResource<LangProvider>("DemoLangs");
private static string CultureInfoStr;
@@ -27,7 +27,7 @@ namespace HandyControlDemo.Properties.Langs
{
public class LangProvider : INotifyPropertyChanged
{
internal static LangProvider Instance => ResourceHelper.GetResource<LangProvider>("DemoLangs");
internal static LangProvider Instance { get; } = ResourceHelper.GetResource<LangProvider>("DemoLangs");
private static string CultureInfoStr;
@@ -81,4 +81,4 @@ namespace HandyControlDemo.Properties.Langs
<#}#>
}
}
}
@@ -11,7 +11,7 @@ namespace HandyControlDemo.Resources
public override ResourceDictionary GetSkin(SkinType skinType) =>
ResourceHelper.GetSkin(typeof(App).Assembly, "Resources/Themes", skinType);
public override ResourceDictionary GetTheme() => new ResourceDictionary
public override ResourceDictionary GetTheme() => new()
{
Source = new Uri("pack://application:,,,/HandyControlDemo;component/Resources/Themes/Theme.xaml")
};
@@ -18,7 +18,7 @@ namespace HandyControlDemo.Service
{
internal ObservableCollection<TabControlDemoModel> GetTabControlDemoDataList()
{
return new ObservableCollection<TabControlDemoModel>
return new()
{
new TabControlDemoModel
{
@@ -139,7 +139,7 @@ namespace HandyControlDemo.Service
internal List<AvatarModel> GetBlogDataList()
{
return new List<AvatarModel>
return new()
{
new AvatarModel
{
@@ -170,7 +170,7 @@ namespace HandyControlDemo.Service
internal List<AvatarModel> GetProjectDataList()
{
return new List<AvatarModel>
return new()
{
new AvatarModel
{
@@ -195,7 +195,7 @@ namespace HandyControlDemo.Service
internal List<AvatarModel> GetWebsiteDataList()
{
return new List<AvatarModel>
return new()
{
new AvatarModel
{
@@ -208,7 +208,7 @@ namespace HandyControlDemo.Service
internal ObservableCollection<CardModel> GetCardDataList()
{
return new ObservableCollection<CardModel>
return new()
{
new CardModel
{
@@ -275,7 +275,7 @@ namespace HandyControlDemo.Service
internal CardModel GetCardData()
{
return new CardModel
return new()
{
Content = $"/HandyControlDemo;component/Resources/Img/Album/{DateTime.Now.Second % 10 + 1}.jpg"
};
@@ -283,7 +283,7 @@ namespace HandyControlDemo.Service
internal List<StepBarDemoModel> GetStepBarDemoDataList()
{
return new List<StepBarDemoModel>
return new()
{
new StepBarDemoModel
{
@@ -310,7 +310,7 @@ namespace HandyControlDemo.Service
internal ObservableCollection<CoverViewDemoModel> GetCoverViewDemoDataList()
{
return new ObservableCollection<CoverViewDemoModel>
return new()
{
new CoverViewDemoModel
{
@@ -20,7 +20,7 @@ namespace HandyControlDemo.Tools.Converter
{
if (value is HatchStyle style)
{
return _brushGenerator.GetHatchBrush(style, ResourceHelper.GetResource<Color>(ResourceToken.DarkPrimaryColor), ResourceHelper.GetResource<Color>(ResourceToken.BackgroundColor));
return _brushGenerator.GetHatchBrush(style, ResourceHelper.GetResource<Color>(ResourceToken.DarkPrimaryColor), Colors.Transparent);
}
return Brushes.Transparent;
}
@@ -7,7 +7,7 @@ namespace HandyControlDemo.Tools
{
private static readonly string NameSpaceStr = typeof(AssemblyHelper).Assembly.GetName().Name;
private static readonly Dictionary<string, object> CacheDic = new Dictionary<string, object>();
private static readonly Dictionary<string, object> CacheDic = new();
public static void Register(string name, object instance) => CacheDic[name] = instance;
@@ -45,7 +45,7 @@
</hc:ScrollViewer>
</Border>
<Border Grid.Row="1" BorderThickness="1" BorderBrush="{DynamicResource BorderBrush}" Margin="0,16,0,0">
<hc:ScrollViewer IsInertiaEnabled="True">
<hc:ScrollViewer IsInertiaEnabled="True" hc:ScrollViewerAttach.AutoHide="False">
<WrapPanel Orientation="Horizontal">
<Border Style="{StaticResource BorderRegion}" Width="200" Height="200" Margin="10,10,32,10">
<Border Background="{DynamicResource PrimaryBrush}">
@@ -4,7 +4,6 @@
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:langs="clr-namespace:HandyControlDemo.Properties.Langs"
xmlns:ex="clr-namespace:HandyControlDemo.Tools.Extension"
xmlns:userControl="clr-namespace:HandyControlDemo.UserControl"
DataContext="{Binding SplitButtonDemo,Source={StaticResource Locator}}">
<hc:TransitioningContentControl>
<StackPanel Margin="32" VerticalAlignment="Center">
@@ -67,17 +67,17 @@ namespace HandyControlDemo.UserControl
var textEditorCustomStyle = ResourceHelper.GetResource<Style>("TextEditorCustom");
_textEditor = new Dictionary<string, TextEditor>
{
["XAML"] = new TextEditor
["XAML"] = new()
{
Style = textEditorCustomStyle,
SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("XML")
},
["C#"] = new TextEditor
["C#"] = new()
{
Style = textEditorCustomStyle,
SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#")
},
["VM"] = new TextEditor
["VM"] = new()
{
Style = textEditorCustomStyle,
SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#")
@@ -1,5 +1,4 @@
<Border xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:hc="https://handyorg.github.io/handycontrol"
BorderThickness="0,1,0,0"
BorderBrush="{DynamicResource BorderBrush}"
Background="{StaticResource CloudDrawingBrush}"
@@ -14,8 +13,5 @@
<userControl:LeftMainContent/>
<userControl:MainContent Grid.Column="1"/>
<GridSplitter Margin="0,26,0,26" Grid.Column="0" HorizontalAlignment="Right" Width="4" Background="Transparent"/>
<hc:ScrollViewer Grid.Column="1" VerticalScrollBarVisibility="Hidden" HorizontalAlignment="Right" IsInertiaEnabled="True" IsPenetrating="True">
<StackPanel hc:Growl.GrowlParent="True" VerticalAlignment="Top" Margin="0,10,10,10"/>
</hc:ScrollViewer>
</Grid>
</Border>
</Border>
@@ -24,7 +24,7 @@
<Path Data="{StaticResource NugetGeometry}" Fill="#30a5dd" Stretch="Uniform"/>
</MenuItem.Icon>
</MenuItem>
<MenuItem Command="hc:ControlCommands.OpenLink" CommandParameter="https://marketplace.visualstudio.com/items?itemName=HandyOrg.handycontrolforvs2019" Header="{ex:Lang Key={x:Static langs:LangKeys.Vsix}}">
<MenuItem Command="hc:ControlCommands.OpenLink" CommandParameter="https://marketplace.visualstudio.com/items?itemName=HandyOrg.HandyControl" Header="{ex:Lang Key={x:Static langs:LangKeys.Vsix}}">
<MenuItem.Icon>
<Path Data="{StaticResource VisualStudioGeometry}" Fill="{DynamicResource PrimaryTextBrush}" Stretch="Uniform"/>
</MenuItem.Icon>
@@ -10,13 +10,13 @@ namespace HandyControlDemo.UserControl
{
public partial class GeometryDemoCtl
{
private readonly HashSet<string> _lineSet = new HashSet<string>
private readonly HashSet<string> _lineSet = new()
{
"CheckedGeometry"
};
public ObservableCollection<GeometryItemModel> GeometryItems { get; set; } =
new ObservableCollection<GeometryItemModel>();
new();
public GeometryDemoCtl()
{
@@ -43,7 +43,7 @@
<TextBlock HorizontalAlignment="Left" Margin="5" Text="{ex:Lang Key={x:Static langs:LangKeys.Text},Converter={StaticResource StringRepeatConverter},ConverterParameter=20}" Style="{StaticResource TextBlockDefaultDanger}"/>
<TextBlock HorizontalAlignment="Left" Margin="5" Text="{ex:Lang Key={x:Static langs:LangKeys.Text},Converter={StaticResource StringRepeatConverter},ConverterParameter=20}" Style="{StaticResource TextBlockDefaultWarning}"/>
<TextBlock HorizontalAlignment="Left" Margin="5" Text="{ex:Lang Key={x:Static langs:LangKeys.Text},Converter={StaticResource StringRepeatConverter},ConverterParameter=20}" Style="{StaticResource TextBlockDefaultInfo}"/>
<TextBlock hc:TextBlockAttach.AutoTooltip="True" Width="300" HorizontalAlignment="Left" Margin="5" Text="{ex:Lang Key={x:Static langs:LangKeys.Text},Converter={StaticResource StringRepeatConverter},ConverterParameter=20}" Style="{StaticResource TextBlockDefaultSuccess}"/>
<TextBlock hc:TextBlockAttach.AutoTooltip="True" TextTrimming="CharacterEllipsis" Width="300" HorizontalAlignment="Left" Margin="5" Text="{ex:Lang Key={x:Static langs:LangKeys.Text},Converter={StaticResource StringRepeatConverter},ConverterParameter=20}" Style="{StaticResource TextBlockDefaultSuccess}"/>
</StackPanel>
</StackPanel>
</hc:TransitioningContentControl>
@@ -24,7 +24,7 @@ namespace HandyControlDemo.ViewModel
private readonly string _id = Guid.NewGuid().ToString();
private readonly Stopwatch _stopwatch = new Lazy<Stopwatch>(() => new Stopwatch()).Value;
private readonly Stopwatch _stopwatch = new();
public ChatBoxViewModel()
{
@@ -50,10 +50,9 @@ namespace HandyControlDemo.ViewModel
#endif
}
public ObservableCollection<ChatInfoModel> ChatInfos { get; set; } = new ObservableCollection<ChatInfoModel>();
public ObservableCollection<ChatInfoModel> ChatInfos { get; set; } = new();
public RelayCommand<KeyEventArgs> SendStringCmd => new Lazy<RelayCommand<KeyEventArgs>>(() =>
new RelayCommand<KeyEventArgs>(SendString)).Value;
public RelayCommand<KeyEventArgs> SendStringCmd => new(SendString);
private void SendString(KeyEventArgs e)
{
@@ -73,12 +72,11 @@ namespace HandyControlDemo.ViewModel
}
}
public RelayCommand<RoutedEventArgs> ReadMessageCmd => new Lazy<RelayCommand<RoutedEventArgs>>(() =>
new RelayCommand<RoutedEventArgs>(ReadMessage)).Value;
public RelayCommand<RoutedEventArgs> ReadMessageCmd => new(ReadMessage);
private void ReadMessage(RoutedEventArgs e)
{
if (e.OriginalSource is FrameworkElement element && element.Tag is ChatInfoModel info)
if (e.OriginalSource is FrameworkElement { Tag: ChatInfoModel info })
{
if (info.Type == ChatMessageType.Image)
{
@@ -95,8 +93,7 @@ namespace HandyControlDemo.ViewModel
}
}
public RelayCommand StartRecordCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(StartRecord)).Value;
public RelayCommand StartRecordCmd => new(StartRecord);
private void StartRecord()
{
@@ -111,8 +108,7 @@ namespace HandyControlDemo.ViewModel
_stopwatch.Start();
}
public RelayCommand StopRecordCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(StopRecord)).Value;
public RelayCommand StopRecordCmd => new(StopRecord);
private void StopRecord()
{
@@ -149,8 +145,7 @@ namespace HandyControlDemo.ViewModel
Messenger.Default.Send(info, MessageToken.SendChatMessage);
}
public RelayCommand OpenImageCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(OpenImage)).Value;
public RelayCommand OpenImageCmd => new(OpenImage);
private void OpenImage()
{
@@ -33,6 +33,6 @@ namespace HandyControlDemo.ViewModel
#endif
}
public RelayCommand CloseCmd => new Lazy<RelayCommand>(() => new RelayCommand(() => CloseAction?.Invoke())).Value;
public RelayCommand CloseCmd => new(() => CloseAction?.Invoke());
}
}
@@ -1,5 +1,4 @@
using System;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
namespace HandyControlDemo.ViewModel
@@ -18,7 +17,6 @@ namespace HandyControlDemo.ViewModel
#endif
}
public RelayCommand CountCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Count++)).Value;
public RelayCommand CountCmd => new(() => Count++);
}
}
@@ -1,5 +1,4 @@
using System;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Command;
using HandyControlDemo.Data;
using HandyControlDemo.Service;
@@ -15,16 +14,14 @@ namespace HandyControlDemo.ViewModel
DataList = dataService.GetCardDataList();
}
public RelayCommand AddItemCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => DataList.Insert(0, _dataService.GetCardData()))).Value;
public RelayCommand AddItemCmd => new(() => DataList.Insert(0, _dataService.GetCardData()));
public RelayCommand RemoveItemCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() =>
public RelayCommand RemoveItemCmd => new(() =>
{
if (DataList.Count > 0)
{
if (DataList.Count > 0)
{
DataList.RemoveAt(0);
}
})).Value;
DataList.RemoveAt(0);
}
});
}
}
@@ -27,8 +27,7 @@ namespace HandyControlDemo.ViewModel
#endif
}
public RelayCommand<FrameworkElement> ShowTextCmd => new Lazy<RelayCommand<FrameworkElement>>(() =>
new RelayCommand<FrameworkElement>(ShowText)).Value;
public RelayCommand<FrameworkElement> ShowTextCmd => new(ShowText);
private void ShowText(FrameworkElement element)
{
@@ -43,8 +42,7 @@ namespace HandyControlDemo.ViewModel
}
#if NET40
public RelayCommand<bool> ShowInteractiveDialogCmd => new Lazy<RelayCommand<bool>>(() =>
new RelayCommand<bool>(ShowInteractiveDialog)).Value;
public RelayCommand<bool> ShowInteractiveDialogCmd => new(ShowInteractiveDialog);
private void ShowInteractiveDialog(bool withTimer)
{
@@ -60,8 +58,7 @@ namespace HandyControlDemo.ViewModel
}
}
#else
public RelayCommand<bool> ShowInteractiveDialogCmd => new Lazy<RelayCommand<bool>>(() =>
new RelayCommand<bool>(async withTimer => await ShowInteractiveDialog(withTimer))).Value;
public RelayCommand<bool> ShowInteractiveDialogCmd => new(async withTimer => await ShowInteractiveDialog(withTimer));
private async Task ShowInteractiveDialog(bool withTimer)
{
@@ -78,13 +75,11 @@ namespace HandyControlDemo.ViewModel
}
#endif
public RelayCommand NewWindowCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => new DialogDemoWindow
{
Owner = Application.Current.MainWindow
}.Show())).Value;
public RelayCommand NewWindowCmd => new(() => new DialogDemoWindow
{
Owner = Application.Current.MainWindow
}.Show());
public RelayCommand<string> ShowWithTokenCmd => new Lazy<RelayCommand<string>>(() =>
new RelayCommand<string>(token => Dialog.Show(new TextDialog(), token))).Value;
public RelayCommand<string> ShowWithTokenCmd => new(token => Dialog.Show(new TextDialog(), token));
}
}
@@ -1,5 +1,4 @@
using System;
using System.Windows;
using System.Windows;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
using HandyControl.Data;
@@ -23,94 +22,79 @@ namespace HandyControlDemo.ViewModel
#region Window
public RelayCommand InfoCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.Info(Properties.Langs.Lang.GrowlInfo, _token))).Value;
public RelayCommand InfoCmd => new(() => Growl.Info(Properties.Langs.Lang.GrowlInfo, _token));
public RelayCommand SuccessCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.Success(Properties.Langs.Lang.GrowlSuccess, _token))).Value;
public RelayCommand SuccessCmd => new(() => Growl.Success(Properties.Langs.Lang.GrowlSuccess, _token));
public RelayCommand WarningCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.Warning(new GrowlInfo
{
Message = Properties.Langs.Lang.GrowlWarning,
CancelStr = Properties.Langs.Lang.Ignore,
ActionBeforeClose = isConfirmed =>
{
Growl.Info(isConfirmed.ToString());
return true;
},
Token = _token
}))).Value;
public RelayCommand ErrorCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.Error(Properties.Langs.Lang.GrowlError, _token))).Value;
public RelayCommand AskCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.Ask(Properties.Langs.Lang.GrowlAsk, isConfirmed =>
public RelayCommand WarningCmd => new(() => Growl.Warning(new GrowlInfo
{
Message = Properties.Langs.Lang.GrowlWarning,
CancelStr = Properties.Langs.Lang.Ignore,
ActionBeforeClose = isConfirmed =>
{
Growl.Info(isConfirmed.ToString());
return true;
}, _token))).Value;
},
Token = _token
}));
public RelayCommand FatalCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.Fatal(new GrowlInfo
{
Message = Properties.Langs.Lang.GrowlFatal,
ShowDateTime = false,
Token = _token
}))).Value;
public RelayCommand ErrorCmd => new(() => Growl.Error(Properties.Langs.Lang.GrowlError, _token));
public RelayCommand ClearCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.Clear(_token))).Value;
public RelayCommand AskCmd => new(() => Growl.Ask(Properties.Langs.Lang.GrowlAsk, isConfirmed =>
{
Growl.Info(isConfirmed.ToString());
return true;
}, _token));
public RelayCommand FatalCmd => new(() => Growl.Fatal(new GrowlInfo
{
Message = Properties.Langs.Lang.GrowlFatal,
ShowDateTime = false,
Token = _token
}));
public RelayCommand ClearCmd => new(() => Growl.Clear(_token));
#endregion
#region Desktop
public RelayCommand InfoGlobalCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.InfoGlobal(Properties.Langs.Lang.GrowlInfo))).Value;
public RelayCommand InfoGlobalCmd => new(() => Growl.InfoGlobal(Properties.Langs.Lang.GrowlInfo));
public RelayCommand SuccessGlobalCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.SuccessGlobal(Properties.Langs.Lang.GrowlSuccess))).Value;
public RelayCommand SuccessGlobalCmd => new(() => Growl.SuccessGlobal(Properties.Langs.Lang.GrowlSuccess));
public RelayCommand WarningGlobalCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.WarningGlobal(new GrowlInfo
{
Message = Properties.Langs.Lang.GrowlWarning,
CancelStr = Properties.Langs.Lang.Ignore,
ActionBeforeClose = isConfirmed =>
{
Growl.InfoGlobal(isConfirmed.ToString());
return true;
}
}))).Value;
public RelayCommand ErrorGlobalCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.ErrorGlobal(Properties.Langs.Lang.GrowlError))).Value;
public RelayCommand AskGlobalCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.AskGlobal(Properties.Langs.Lang.GrowlAsk, isConfirmed =>
public RelayCommand WarningGlobalCmd => new(() => Growl.WarningGlobal(new GrowlInfo
{
Message = Properties.Langs.Lang.GrowlWarning,
CancelStr = Properties.Langs.Lang.Ignore,
ActionBeforeClose = isConfirmed =>
{
Growl.InfoGlobal(isConfirmed.ToString());
return true;
}))).Value;
}
}));
public RelayCommand FatalGlobalCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.FatalGlobal(new GrowlInfo
{
Message = Properties.Langs.Lang.GrowlFatal,
ShowDateTime = false
}))).Value;
public RelayCommand ErrorGlobalCmd => new(() => Growl.ErrorGlobal(Properties.Langs.Lang.GrowlError));
public RelayCommand ClearGlobalCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(Growl.ClearGlobal)).Value;
public RelayCommand AskGlobalCmd => new(() => Growl.AskGlobal(Properties.Langs.Lang.GrowlAsk, isConfirmed =>
{
Growl.InfoGlobal(isConfirmed.ToString());
return true;
}));
public RelayCommand FatalGlobalCmd => new(() => Growl.FatalGlobal(new GrowlInfo
{
Message = Properties.Langs.Lang.GrowlFatal,
ShowDateTime = false
}));
public RelayCommand ClearGlobalCmd => new(Growl.ClearGlobal);
#endregion
public RelayCommand NewWindowCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => new GrowlDemoWindow
{
Owner = Application.Current.MainWindow
}.Show())).Value;
public RelayCommand NewWindowCmd => new(() => new GrowlDemoWindow
{
Owner = Application.Current.MainWindow
}.Show());
}
}
@@ -6,8 +6,7 @@ namespace HandyControlDemo.ViewModel
{
public class ImageBrowserDemoViewModel
{
public RelayCommand OpenImgCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() =>
new ImageBrowser(new Uri("pack://application:,,,/Resources/Img/1.jpg")).Show())).Value;
public RelayCommand OpenImgCmd => new(() =>
new ImageBrowser(new Uri("pack://application:,,,/Resources/Img/1.jpg")).Show());
}
}
@@ -1,5 +1,4 @@
using System;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
using HandyControl.Data;
@@ -9,8 +8,7 @@ namespace HandyControlDemo.ViewModel
{
public class NotificationDemoViewModel : ViewModelBase
{
public RelayCommand OpenCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Notification.Show(new AppNotification(), ShowAnimation, StaysOpen))).Value;
public RelayCommand OpenCmd => new(() => Notification.Show(new AppNotification(), ShowAnimation, StaysOpen));
private ShowAnimation _showAnimation;
@@ -93,11 +93,9 @@ namespace HandyControlDemo.ViewModel
#endif
}
public RelayCommand<object> MouseCmd => new Lazy<RelayCommand<object>>(() =>
new RelayCommand<object>(str => Growl.Info(str.ToString()))).Value;
public RelayCommand<object> MouseCmd => new(str => Growl.Info(str.ToString()));
public RelayCommand SendNotificationCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(SendNotification)).Value;
public RelayCommand SendNotificationCmd => new(SendNotification);
private void SendNotification()
{
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using GalaSoft.MvvmLight.Command;
using HandyControl.Data;
@@ -42,9 +41,7 @@ namespace HandyControlDemo.ViewModel
/// <summary>
/// 页码改变命令
/// </summary>
public RelayCommand<FunctionEventArgs<int>> PageUpdatedCmd =>
new Lazy<RelayCommand<FunctionEventArgs<int>>>(() =>
new RelayCommand<FunctionEventArgs<int>>(PageUpdated)).Value;
public RelayCommand<FunctionEventArgs<int>> PageUpdatedCmd => new(PageUpdated);
/// <summary>
/// 页码改变
@@ -1,5 +1,4 @@
using System;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
@@ -7,8 +6,7 @@ namespace HandyControlDemo.ViewModel
{
public class SearchBarDemoViewModel : ViewModelBase
{
public RelayCommand<string> SearchCmd => new Lazy<RelayCommand<string>>(() =>
new RelayCommand<string>(Search)).Value;
public RelayCommand<string> SearchCmd => new(Search);
private void Search(string key)
{
@@ -1,5 +1,4 @@
using System;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
using HandyControl.Data;
@@ -8,13 +7,11 @@ namespace HandyControlDemo.ViewModel
{
public class SideMenuDemoViewModel : ViewModelBase
{
public RelayCommand<FunctionEventArgs<object>> SwitchItemCmd => new Lazy<RelayCommand<FunctionEventArgs<object>>>(() =>
new RelayCommand<FunctionEventArgs<object>>(SwitchItem)).Value;
public RelayCommand<FunctionEventArgs<object>> SwitchItemCmd => new(SwitchItem);
private void SwitchItem(FunctionEventArgs<object> info) => Growl.Info((info.Info as SideMenuItem)?.Header.ToString());
public RelayCommand<string> SelectCmd => new Lazy<RelayCommand<string>>(() =>
new RelayCommand<string>(Select)).Value;
public RelayCommand<string> SelectCmd => new(Select);
private void Select(string header) => Growl.Success(header);
}
@@ -1,5 +1,4 @@
using System;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
@@ -7,7 +6,6 @@ namespace HandyControlDemo.ViewModel
{
public class SplitButtonDemoViewModel : ViewModelBase
{
public RelayCommand<string> SelectCmd => new Lazy<RelayCommand<string>>(() =>
new RelayCommand<string>(str => Growl.Info(str))).Value;
public RelayCommand<string> SelectCmd => new(str => Growl.Info(str));
}
}
@@ -1,5 +1,4 @@
using System;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
using HandyControlDemo.UserControl;
@@ -7,7 +6,6 @@ namespace HandyControlDemo.ViewModel
{
public class SpriteDemoViewModel
{
public RelayCommand OpenCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Sprite.Show(new AppSprite()))).Value;
public RelayCommand OpenCmd => new(() => Sprite.Show(new AppSprite()));
}
}
@@ -1,5 +1,4 @@
using System;
using System.Linq;
using System.Linq;
using System.Windows.Controls;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
@@ -27,12 +26,12 @@ namespace HandyControlDemo.ViewModel
/// <summary>
/// 下一步
/// </summary>
public RelayCommand<Panel> NextCmd => new Lazy<RelayCommand<Panel>>(() => new RelayCommand<Panel>(Next)).Value;
public RelayCommand<Panel> NextCmd => new(Next);
/// <summary>
/// 上一步
/// </summary>
public RelayCommand<Panel> PrevCmd => new Lazy<RelayCommand<Panel>>(() => new RelayCommand<Panel>(Prev)).Value;
public RelayCommand<Panel> PrevCmd => new(Prev);
private void Next(Panel panel)
{
@@ -1,5 +1,4 @@
using System;
using System.Windows;
using System.Windows;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
using HandyControl.Data;
@@ -12,16 +11,14 @@ namespace HandyControlDemo.ViewModel
{
public TabControlDemoViewModel(DataService dataService) => DataList = dataService.GetTabControlDemoDataList();
public RelayCommand<CancelRoutedEventArgs> ClosingCmd => new Lazy<RelayCommand<CancelRoutedEventArgs>>(() =>
new RelayCommand<CancelRoutedEventArgs>(Closing)).Value;
public RelayCommand<CancelRoutedEventArgs> ClosingCmd => new(Closing);
private void Closing(CancelRoutedEventArgs args)
{
Growl.Info($"{(args.OriginalSource as TabItem)?.Header} Closing");
}
public RelayCommand<RoutedEventArgs> ClosedCmd => new Lazy<RelayCommand<RoutedEventArgs>>(() =>
new RelayCommand<RoutedEventArgs>(Closed)).Value;
public RelayCommand<RoutedEventArgs> ClosedCmd => new(Closed);
private void Closed(RoutedEventArgs args)
{
@@ -1,5 +1,4 @@
using System;
using System.Collections.ObjectModel;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
@@ -30,21 +29,20 @@ namespace HandyControlDemo.ViewModel
#endif
}
public RelayCommand AddItemCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() =>
public RelayCommand AddItemCmd => new(() =>
{
if (string.IsNullOrEmpty(TagName))
{
if (string.IsNullOrEmpty(TagName))
{
Growl.Warning(Lang.PlsEnterContent);
return;
}
Growl.Warning(Lang.PlsEnterContent);
return;
}
DataList.Insert(0, new DemoDataModel
{
IsSelected = DataList.Count % 2 == 0,
Name = TagName
});
TagName = string.Empty;
})).Value;
DataList.Insert(0, new DemoDataModel
{
IsSelected = DataList.Count % 2 == 0,
Name = TagName
});
TagName = string.Empty;
});
}
}
@@ -1,5 +1,4 @@
using System;
using System.Windows;
using System.Windows;
using GalaSoft.MvvmLight.Command;
using HandyControlDemo.Tools;
@@ -7,7 +6,7 @@ namespace HandyControlDemo.ViewModel
{
public class WindowDemoViewModel
{
public RelayCommand<string> OpenWindowCmd => new Lazy<RelayCommand<string>>(() => new RelayCommand<string>(OpenWindow)).Value;
public RelayCommand<string> OpenWindowCmd => new(OpenWindow);
private void OpenWindow(string windowTag)
{
@@ -89,24 +89,18 @@ namespace HandyControlDemo.ViewModel
/// <summary>
/// 切换例子命令
/// </summary>
public RelayCommand<SelectionChangedEventArgs> SwitchDemoCmd =>
new Lazy<RelayCommand<SelectionChangedEventArgs>>(() =>
new RelayCommand<SelectionChangedEventArgs>(SwitchDemo)).Value;
public RelayCommand<SelectionChangedEventArgs> SwitchDemoCmd => new(SwitchDemo);
public RelayCommand OpenPracticalDemoCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(OpenPracticalDemo)).Value;
public RelayCommand OpenPracticalDemoCmd => new(OpenPracticalDemo);
public RelayCommand GlobalShortcutInfoCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.Info("Global Shortcut Info"))).Value;
public RelayCommand GlobalShortcutInfoCmd => new(() => Growl.Info("Global Shortcut Info"));
public RelayCommand GlobalShortcutWarningCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.Warning("Global Shortcut Warning"))).Value;
public RelayCommand GlobalShortcutWarningCmd => new(() => Growl.Warning("Global Shortcut Warning"));
public RelayCommand OpenDocCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() =>
{
ControlCommands.OpenLink.Execute(_dataService.GetDemoUrl(DemoInfoCurrent, DemoItemCurrent));
})).Value;
public RelayCommand OpenDocCmd => new(() =>
{
ControlCommands.OpenLink.Execute(_dataService.GetDemoUrl(DemoInfoCurrent, DemoItemCurrent));
});
#endregion
@@ -1,5 +1,4 @@
using System;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using HandyControlDemo.Data;
@@ -14,8 +13,7 @@ namespace HandyControlDemo.ViewModel
VersionInfo = VersionHelper.GetVersion();
}
public RelayCommand<string> OpenViewCmd => new Lazy<RelayCommand<string>>(() =>
new RelayCommand<string>(OpenView)).Value;
public RelayCommand<string> OpenViewCmd => new(OpenView);
private void OpenView(string viewName)
{
@@ -58,7 +58,7 @@ namespace HandyControlDemo.ViewModel
public WindowDemoViewModel WindowDemo => SimpleIoc.Default.GetInstance<WindowDemoViewModel>();
public ItemsDisplayViewModel ContributorsView => new ItemsDisplayViewModel(SimpleIoc.Default.GetInstance<DataService>().GetContributorDataList);
public ItemsDisplayViewModel ContributorsView => new(SimpleIoc.Default.GetInstance<DataService>().GetContributorDataList);
public ItemsDisplayViewModel BlogsView => SimpleIoc.Default.GetInstance<ItemsDisplayViewModel>("Blogs");
@@ -70,7 +70,7 @@ namespace HandyControlDemo.ViewModel
public PaginationDemoViewModel PaginationDemo => SimpleIoc.Default.GetInstance<PaginationDemoViewModel>();
public ChatBoxViewModel ChatBox => new ChatBoxViewModel();
public ChatBoxViewModel ChatBox => new();
public CoverViewModel CoverView => SimpleIoc.Default.GetInstance<CoverViewModel>();
@@ -86,11 +86,11 @@ namespace HandyControlDemo.ViewModel
public SideMenuDemoViewModel SideMenuDemo => SimpleIoc.Default.GetInstance<SideMenuDemoViewModel>();
public TabControlDemoViewModel TabControlDemo => new TabControlDemoViewModel(SimpleIoc.Default.GetInstance<DataService>());
public TabControlDemoViewModel TabControlDemo => new(SimpleIoc.Default.GetInstance<DataService>());
public NonClientAreaViewModel NoUser => SimpleIoc.Default.GetInstance<NonClientAreaViewModel>();
public CardDemoViewModel CardDemo => new CardDemoViewModel(SimpleIoc.Default.GetInstance<DataService>());
public CardDemoViewModel CardDemo => new(SimpleIoc.Default.GetInstance<DataService>());
public SpriteDemoViewModel SpriteDemo => SimpleIoc.Default.GetInstance<SpriteDemoViewModel>();
@@ -98,7 +98,7 @@ namespace HandyControlDemo.ViewModel
public SplitButtonDemoViewModel SplitButtonDemo => SimpleIoc.Default.GetInstance<SplitButtonDemoViewModel>();
public TagDemoViewModel TagDemo => new TagDemoViewModel(SimpleIoc.Default.GetInstance<DataService>());
public TagDemoViewModel TagDemo => new(SimpleIoc.Default.GetInstance<DataService>());
#endregion
}
@@ -9,7 +9,7 @@ namespace HandyControl.Collections
[Serializable]
public class ManualObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
private readonly SimpleMonitor _monitor = new SimpleMonitor();
private readonly SimpleMonitor _monitor = new();
private const string CountString = "Count";
@@ -258,50 +258,45 @@ namespace HandyControl.Controls
private static void OnShowRowNumberChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
if (!(target is DataGrid dataGrid)) return;
if (target is not DataGrid dataGrid) return;
var show = (bool) e.NewValue;
if (show)
{
dataGrid.LoadingRow += DataGrid_LoadingRow;
dataGrid.ItemContainerGenerator.ItemsChanged += ItemContainerGenerator_ItemsChanged;
dataGrid.ItemContainerGenerator.ItemsChanged += ItemContainerGeneratorItemsChanged;
}
else
{
dataGrid.LoadingRow -= DataGrid_LoadingRow;
dataGrid.ItemContainerGenerator.ItemsChanged -= ItemContainerGenerator_ItemsChanged;
dataGrid.ItemContainerGenerator.ItemsChanged -= ItemContainerGeneratorItemsChanged;
}
UpdateItems(dataGrid.ItemContainerGenerator, dataGrid.Items.Count, show);
}
private static void ItemContainerGenerator_ItemsChanged(object sender, ItemsChangedEventArgs e)
{
if (!(sender is ItemContainerGenerator generator)) return;
UpdateItems(generator, e.ItemCount);
}
private static void UpdateItems(ItemContainerGenerator generator, int itemsCount, bool show = true)
{
if (show)
void ItemContainerGeneratorItemsChanged(object sender, ItemsChangedEventArgs e)
{
for (var i = 0; i < itemsCount; i++)
var generator = dataGrid.ItemContainerGenerator;
var itemsCount = dataGrid.Items.Count;
if (show)
{
var row = (DataGridRow) generator.ContainerFromIndex(i);
if (row != null)
for (var i = 0; i < itemsCount; i++)
{
row.Header = (i + 1).ToString();
var row = (DataGridRow) generator.ContainerFromIndex(i);
if (row != null)
{
row.Header = (i + 1).ToString();
}
}
}
}
else
{
for (var i = 0; i < itemsCount; i++)
else
{
var row = (DataGridRow) generator.ContainerFromIndex(i);
if (row != null)
for (var i = 0; i < itemsCount; i++)
{
row.Header = null;
var row = (DataGridRow) generator.ContainerFromIndex(i);
if (row != null)
{
row.Header = null;
}
}
}
}
@@ -337,7 +332,7 @@ namespace HandyControl.Controls
}
public static void SetCanUnselectAllWithBlankArea(DependencyObject element, bool value)
=> element.SetValue(CanUnselectAllWithBlankAreaProperty, value);
=> element.SetValue(CanUnselectAllWithBlankAreaProperty, ValueBoxes.BooleanBox(value));
public static bool GetCanUnselectAllWithBlankArea(DependencyObject element)
=> (bool) element.GetValue(CanUnselectAllWithBlankAreaProperty);
@@ -20,7 +20,7 @@ namespace HandyControl.Controls
new FrameworkPropertyMetadata(ValueBoxes.FalseBox, FrameworkPropertyMetadataOptions.Inherits));
public static void SetAutoWidth(DependencyObject element, bool value)
=> element.SetValue(AutoWidthProperty, value);
=> element.SetValue(AutoWidthProperty, ValueBoxes.BooleanBox(value));
public static bool GetAutoWidth(DependencyObject element)
=> (bool) element.GetValue(AutoWidthProperty);
@@ -0,0 +1,96 @@
using System;
using System.Windows;
using System.Windows.Controls;
namespace HandyControl.Controls
{
public class GridAttach
{
public static readonly DependencyProperty NameProperty = DependencyProperty.RegisterAttached(
"Name", typeof(string), typeof(GridAttach), new PropertyMetadata(default(string)));
public static void SetName(DependencyObject element, string value)
=> element.SetValue(NameProperty, value);
public static string GetName(DependencyObject element)
=> (string) element.GetValue(NameProperty);
public static readonly DependencyProperty RowNameProperty = DependencyProperty.RegisterAttached(
"RowName", typeof(string), typeof(GridAttach), new PropertyMetadata(default(string), OnRowNameChanged));
private static void OnRowNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is FrameworkElement frameworkElement)
{
if (e.NewValue is string rowName)
{
if (string.IsNullOrEmpty(rowName))
{
return;
}
if (frameworkElement.Parent is Grid grid)
{
for (var i = 0; i < grid.RowDefinitions.Count; i++)
{
var gridRowDefinition = grid.RowDefinitions[i];
var gridRowName = GetName(gridRowDefinition);
if (!string.IsNullOrEmpty(gridRowName) &&
gridRowName.Equals(rowName, StringComparison.Ordinal))
{
Grid.SetRow(frameworkElement, i);
return;
}
}
}
}
}
}
public static void SetRowName(DependencyObject element, string value)
=> element.SetValue(RowNameProperty, value);
public static string GetRowName(DependencyObject element)
=> (string) element.GetValue(RowNameProperty);
public static readonly DependencyProperty ColumnNameProperty = DependencyProperty.RegisterAttached(
"ColumnName", typeof(string), typeof(GridAttach), new PropertyMetadata(default(string), OnColumnNameChanged));
private static void OnColumnNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is FrameworkElement frameworkElement)
{
if (e.NewValue is string columnName)
{
if (string.IsNullOrEmpty(columnName))
{
return;
}
if (frameworkElement.Parent is Grid grid)
{
for (var i = 0; i < grid.ColumnDefinitions.Count; i++)
{
var gridColumnDefinition = grid.ColumnDefinitions[i];
var gridColumnName = GetName(gridColumnDefinition);
if (!string.IsNullOrEmpty(gridColumnName) &&
gridColumnName.Equals(columnName, StringComparison.Ordinal))
{
Grid.SetColumn(frameworkElement, i);
return;
}
}
}
}
}
}
public static void SetColumnName(DependencyObject element, string value)
=> element.SetValue(ColumnNameProperty, value);
public static string GetColumnName(DependencyObject element)
=> (string) element.GetValue(ColumnNameProperty);
}
}
@@ -16,13 +16,10 @@ namespace HandyControl.Controls
{
var topLine = (FrameworkElement) d;
if (e.NewValue is Popup popup)
if (e.NewValue is Popup { TemplatedParent: MenuItem menuItem })
{
if (popup.TemplatedParent is MenuItem menuItem)
{
SetTopLine(menuItem, topLine);
menuItem.Loaded += MenuItem_Loaded;
}
SetTopLine(menuItem, topLine);
menuItem.Loaded += MenuItem_Loaded;
}
}
@@ -0,0 +1,17 @@
using System.Windows;
using HandyControl.Data;
namespace HandyControl.Controls
{
public class ScrollViewerAttach
{
public static readonly DependencyProperty AutoHideProperty = DependencyProperty.RegisterAttached(
"AutoHide", typeof(bool), typeof(ScrollViewerAttach), new FrameworkPropertyMetadata(ValueBoxes.TrueBox, FrameworkPropertyMetadataOptions.Inherits));
public static void SetAutoHide(DependencyObject element, bool value)
=> element.SetValue(AutoHideProperty, value);
public static bool GetAutoHide(DependencyObject element)
=> (bool) element.GetValue(AutoHideProperty);
}
}
@@ -1,6 +1,9 @@
using System.Windows;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using HandyControl.Data;
using HandyControl.Tools.Helper;
namespace HandyControl.Controls
{
@@ -15,13 +18,11 @@ namespace HandyControl.Controls
{
if ((bool) e.NewValue)
{
ctl.TextTrimming = TextTrimming.WordEllipsis;
UpdateTooltip(ctl);
ctl.SizeChanged += TextBlock_SizeChanged;
}
else
{
ctl.ClearValue(TextBlock.TextTrimmingProperty);
ctl.SizeChanged -= TextBlock_SizeChanged;
}
}
@@ -46,8 +47,25 @@ namespace HandyControl.Controls
textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
var width = textBlock.DesiredSize.Width - textBlock.Margin.Left - textBlock.Margin.Right;
ToolTipService.SetToolTip(textBlock,
textBlock.RenderSize.Width > width || textBlock.ActualWidth < width ? textBlock.Text : null);
// the code Math.Abs(CalcTextWidth(textBlock) - width) > 1 is not elegant end even bugly,
// while it does solve the problem of Tooltip failure in some cases
if (textBlock.RenderSize.Width > width || textBlock.ActualWidth < width || Math.Abs(CalcTextWidth(textBlock) - width) > 1)
{
ToolTipService.SetToolTip(textBlock, textBlock.Text);
}
else
{
ToolTipService.SetToolTip(textBlock, null);
}
}
private static double CalcTextWidth(TextBlock textBlock)
{
var formattedText = TextHelper.CreateFormattedText(textBlock.Text, textBlock.FlowDirection,
new Typeface(textBlock.FontFamily, textBlock.FontStyle, textBlock.FontWeight, textBlock.FontStretch),
textBlock.FontSize);
return formattedText.WidthIncludingTrailingWhitespace;
}
}
}
@@ -141,7 +141,7 @@ namespace HandyControl.Controls
}
public static void SetHideWhenClosing(DependencyObject element, bool value)
=> element.SetValue(HideWhenClosingProperty, value);
=> element.SetValue(HideWhenClosingProperty, ValueBoxes.BooleanBox(value));
public static bool GetHideWhenClosing(DependencyObject element)
=> (bool) element.GetValue(HideWhenClosingProperty);
@@ -33,7 +33,7 @@ namespace HandyControl.Controls
private static void OnInstanceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is FrameworkElement target)) return;
if (d is not FrameworkElement target) return;
var element = (AdornerElement) e.NewValue;
element.OnInstanceChanged(target);
}
@@ -99,7 +99,7 @@ namespace HandyControl.Controls
private static void OnDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is UIElement target)) return;
if (d is not UIElement target) return;
target.PreviewMouseLeftButtonDown -= Target_PreviewMouseLeftButtonDown;
target.PreviewMouseLeftButtonUp -= Target_PreviewMouseLeftButtonUp;
@@ -60,6 +60,6 @@ namespace HandyControl.Controls
return mySize;
}
private static Size ConvertThickness2Size(Thickness th) => new Size(th.Left + th.Right, th.Top + th.Bottom);
private static Size ConvertThickness2Size(Thickness th) => new(th.Left + th.Right, th.Top + th.Bottom);
}
}
@@ -44,9 +44,9 @@ namespace HandyControl.Controls
private DispatcherTimer _updateTimer;
private readonly List<double> _widthList = new List<double>();
private readonly List<double> _widthList = new();
private readonly Dictionary<object, CarouselItem> _entryDic = new Dictionary<object, CarouselItem>();
private readonly Dictionary<object, CarouselItem> _entryDic = new();
private bool _isRefresh;
@@ -101,7 +101,7 @@ namespace HandyControl.Controls
/// <summary>
/// 预设的颜色(一共18个,两行)
/// </summary>
private readonly List<string> _colorPresetList = new List<string>
private readonly List<string> _colorPresetList = new()
{
"#f44336",
"#e91e63",
@@ -127,7 +127,7 @@ namespace HandyControl.Controls
/// <summary>
/// 颜色范围集合
/// </summary>
private readonly List<ColorRange> _colorRangeList = new List<ColorRange>
private readonly List<ColorRange> _colorRangeList = new()
{
new ColorRange
{
@@ -164,7 +164,7 @@ namespace HandyControl.Controls
/// <summary>
/// 颜色分隔集合
/// </summary>
private readonly List<Color> _colorSeparateList = new List<Color>
private readonly List<Color> _colorSeparateList = new()
{
Color.FromRgb(255, 0, 0),
Color.FromRgb(255, 0, 255),
@@ -469,7 +469,7 @@ namespace HandyControl.Controls
var button = new Button
{
Margin = new Thickness(6),
Style = ResourceHelper.GetResource<Style>(ResourceToken.ButtonCustom),
Style = ResourceHelper.GetResourceInternal<Style>(ResourceToken.ButtonCustom),
Content = new Border
{
Background = brush,
@@ -549,7 +549,7 @@ namespace HandyControl.Controls
var cIndex = _colorSeparateList.IndexOf(Color.FromRgb(list[0], list[1], list[2]));
int sub;
var direc = 0;
if (cIndex < 5 && cIndex > 0)
if (cIndex is < 5 and > 0)
{
var nextColorList = _colorSeparateList[cIndex + 1].ToList();
var prevColorList = _colorSeparateList[cIndex - 1].ToList();
@@ -680,29 +680,18 @@ namespace HandyControl.Controls
private void NumericUpDownRgb_OnValueChanged(object sender, FunctionEventArgs<double> e)
{
if (!_appliedTemplate || !IsNeedUpdateInfo) return;
if (e.OriginalSource is NumericUpDown ctl && ctl.Tag is string tag)
if (e.OriginalSource is NumericUpDown { Tag: string tag })
{
var color = SelectedBrush.Color;
IsNeedUpdateInfo = false;
switch (tag)
SelectedBrush = tag switch
{
case "R":
{
SelectedBrush = new SolidColorBrush(Color.FromArgb(color.A, (byte) e.Info, color.G, color.B));
break;
}
case "G":
{
SelectedBrush = new SolidColorBrush(Color.FromArgb(color.A, color.R, (byte) e.Info, color.B));
break;
}
case "B":
{
SelectedBrush = new SolidColorBrush(Color.FromArgb(color.A, color.R, color.G, (byte) e.Info));
break;
}
}
"R" => new SolidColorBrush(Color.FromArgb(color.A, (byte) e.Info, color.G, color.B)),
"G" => new SolidColorBrush(Color.FromArgb(color.A, color.R, (byte) e.Info, color.B)),
"B" => new SolidColorBrush(Color.FromArgb(color.A, color.R, color.G, (byte) e.Info)),
_ => SelectedBrush
};
IsNeedUpdateInfo = true;
}
@@ -722,10 +711,7 @@ namespace HandyControl.Controls
private void ToggleButtonDropper_Click(object sender, RoutedEventArgs e)
{
if (_colorDropper == null)
{
_colorDropper = new ColorDropper(this);
}
_colorDropper ??= new ColorDropper(this);
// ReSharper disable once PossibleInvalidOperationException
_colorDropper.Update(_toggleButtonDropper.IsChecked.Value);
}
@@ -748,6 +734,6 @@ namespace HandyControl.Controls
GC.SuppressFinalize(this);
}
public bool CanDispose { get; } = true;
public bool CanDispose => true;
}
}
@@ -69,12 +69,12 @@ namespace HandyControl.Controls
/// <summary>
/// 存储所有的内容
/// </summary>
private readonly Dictionary<int, object> _contentDic = new Dictionary<int, object>();
private readonly Dictionary<int, object> _contentDic = new();
/// <summary>
/// 当前在显示范围内的项
/// </summary>
private readonly Dictionary<int, CoverFlowItem> _itemShowDic = new Dictionary<int, CoverFlowItem>();
private readonly Dictionary<int, CoverFlowItem> _itemShowDic = new();
/// <summary>
/// 相机
@@ -72,12 +72,12 @@ namespace HandyControl.Controls
var textureCoordinates = new PointCollection
{
new Point(0, 1),
new Point(1, 1),
new Point(1, 0),
new Point(0, 0),
new Point(1, 0),
new Point(1, 1)
new(0, 1),
new(1, 1),
new(1, 0),
new(0, 0),
new(1, 0),
new(1, 1)
};
var normals = new Vector3DCollection
@@ -16,7 +16,7 @@ namespace HandyControl.Controls
private IEnumerable _itemsSourceInternal;
private readonly Dictionary<object, CoverViewItem> _entryDic = new Dictionary<object, CoverViewItem>();
private readonly Dictionary<object, CoverViewItem> _entryDic = new();
private bool _isRefresh;
@@ -16,7 +16,7 @@ namespace HandyControl.Controls
private AdornerContainer _container;
private static readonly Dictionary<string, FrameworkElement> ContainerDic = new Dictionary<string, FrameworkElement>();
private static readonly Dictionary<string, FrameworkElement> ContainerDic = new();
public static readonly DependencyProperty IsClosedProperty = DependencyProperty.Register(
"IsClosed", typeof(bool), typeof(Dialog), new PropertyMetadata(ValueBoxes.FalseBox));
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
@@ -25,7 +26,9 @@ namespace HandyControl.Controls
#region Constants
private const string ElementPanelMore = "PART_PanelMore";
private const string ElementGridMain = "PART_GridMain";
private const string ElementButtonClose = "PART_ButtonClose";
#endregion Constants
@@ -56,7 +59,7 @@ namespace HandyControl.Controls
/// </summary>
private DispatcherTimer _timerClose;
private static readonly Dictionary<string, Panel> PanelDic = new Dictionary<string, Panel>();
private static readonly Dictionary<string, Panel> PanelDic = new();
#endregion Data
@@ -176,15 +179,6 @@ namespace HandyControl.Controls
public static readonly DependencyProperty TypeProperty = DependencyProperty.Register(
"Type", typeof(InfoType), typeof(Growl), new PropertyMetadata(default(InfoType)));
public static readonly DependencyProperty GrowlParentProperty = DependencyProperty.RegisterAttached(
"GrowlParent", typeof(bool), typeof(Growl), new PropertyMetadata(ValueBoxes.FalseBox, (o, args) =>
{
if ((bool) args.NewValue && o is Panel panel)
{
SetGrowlPanel(panel);
}
}));
public static readonly DependencyProperty TokenProperty = DependencyProperty.RegisterAttached(
"Token", typeof(string), typeof(Growl), new PropertyMetadata(default(string), OnTokenChanged));
@@ -209,10 +203,28 @@ namespace HandyControl.Controls
public static string GetToken(DependencyObject element)
=> (string) element.GetValue(TokenProperty);
public static readonly DependencyProperty GrowlParentProperty = DependencyProperty.RegisterAttached(
"GrowlParent", typeof(bool), typeof(Growl), new PropertyMetadata(ValueBoxes.FalseBox, (o, args) =>
{
if ((bool) args.NewValue && o is Panel panel)
{
SetGrowlPanel(panel);
}
}));
public static void SetGrowlParent(DependencyObject element, bool value) => element.SetValue(GrowlParentProperty, ValueBoxes.BooleanBox(value));
public static bool GetGrowlParent(DependencyObject element) => (bool) element.GetValue(GrowlParentProperty);
private static readonly DependencyProperty IsCreatedAutomaticallyProperty = DependencyProperty.RegisterAttached(
"IsCreatedAutomatically", typeof(bool), typeof(Growl), new PropertyMetadata(ValueBoxes.FalseBox));
private static void SetIsCreatedAutomatically(DependencyObject element, bool value)
=> element.SetValue(IsCreatedAutomaticallyProperty, ValueBoxes.BooleanBox(value));
private static bool GetIsCreatedAutomatically(DependencyObject element)
=> (bool) element.GetValue(IsCreatedAutomaticallyProperty);
public InfoType Type
{
get => (InfoType) GetValue(TypeProperty);
@@ -316,7 +328,7 @@ namespace HandyControl.Controls
}
};
PanelElement.SetFluidMoveBehavior(panel, ResourceHelper.GetResource<FluidMoveBehavior>(ResourceToken.BehaviorXY400));
PanelElement.SetFluidMoveBehavior(panel, ResourceHelper.GetResourceInternal<FluidMoveBehavior>(ResourceToken.BehaviorXY400));
}
private void Update()
@@ -331,7 +343,7 @@ namespace HandyControl.Controls
var transform = new TranslateTransform
{
X = MaxWidth
X = FlowDirection == FlowDirection.LeftToRight ? MaxWidth : -MaxWidth
};
_gridMain.RenderTransform = transform;
transform.BeginAnimation(TranslateTransform.XProperty, AnimationHelper.CreateAnimation(0));
@@ -340,28 +352,28 @@ namespace HandyControl.Controls
private static void ShowGlobal(GrowlInfo growlInfo)
{
if (GrowlWindow == null)
{
GrowlWindow = new GrowlWindow();
GrowlWindow.Show();
InitGrowlPanel(GrowlWindow.GrowlPanel);
GrowlWindow.Init();
}
GrowlWindow.Show(true);
Application.Current.Dispatcher?.Invoke(
#if NET40
new Action(
#endif
() =>
{
if (GrowlWindow == null)
{
GrowlWindow = new GrowlWindow();
GrowlWindow.Show();
InitGrowlPanel(GrowlWindow.GrowlPanel);
GrowlWindow.Init();
}
GrowlWindow.Show(true);
var ctl = new Growl
{
Message = growlInfo.Message,
Time = DateTime.Now,
Icon = ResourceHelper.GetResource<Geometry>(growlInfo.IconKey),
IconBrush = ResourceHelper.GetResource<Brush>(growlInfo.IconBrushKey),
Icon = ResourceHelper.GetResourceInternal<Geometry>(growlInfo.IconKey),
IconBrush = ResourceHelper.GetResourceInternal<Brush>(growlInfo.IconBrushKey),
_showCloseButton = growlInfo.ShowCloseButton,
ActionBeforeClose = growlInfo.ActionBeforeClose,
_staysOpen = growlInfo.StaysOpen,
@@ -369,7 +381,8 @@ namespace HandyControl.Controls
ConfirmStr = growlInfo.ConfirmStr,
CancelStr = growlInfo.CancelStr,
Type = growlInfo.Type,
_waitTime = Math.Max(growlInfo.WaitTime, 2)
_waitTime = Math.Max(growlInfo.WaitTime, 2),
FlowDirection = growlInfo.FlowDirection
};
GrowlWindow.GrowlPanel.Children.Insert(0, ctl);
}
@@ -395,8 +408,8 @@ namespace HandyControl.Controls
{
Message = growlInfo.Message,
Time = DateTime.Now,
Icon = ResourceHelper.GetResource<Geometry>(growlInfo.IconKey),
IconBrush = ResourceHelper.GetResource<Brush>(growlInfo.IconBrushKey),
Icon = ResourceHelper.GetResourceInternal<Geometry>(growlInfo.IconKey),
IconBrush = ResourceHelper.GetResourceInternal<Brush>(growlInfo.IconBrushKey),
_showCloseButton = growlInfo.ShowCloseButton,
ActionBeforeClose = growlInfo.ActionBeforeClose,
_staysOpen = growlInfo.StaysOpen,
@@ -406,6 +419,7 @@ namespace HandyControl.Controls
Type = growlInfo.Type,
_waitTime = Math.Max(growlInfo.WaitTime, 2)
};
if (!string.IsNullOrEmpty(growlInfo.Token))
{
if (PanelDic.TryGetValue(growlInfo.Token, out var panel))
@@ -415,6 +429,8 @@ namespace HandyControl.Controls
}
else
{
// GrowlPanel is null, we create it automatically
GrowlPanel ??= CreateDefaultPanel();
GrowlPanel?.Children.Insert(0, ctl);
}
}
@@ -424,6 +440,64 @@ namespace HandyControl.Controls
);
}
private static Panel CreateDefaultPanel()
{
FrameworkElement element = WindowHelper.GetActiveWindow();
var decorator = VisualHelper.GetChild<AdornerDecorator>(element);
if (decorator != null)
{
var layer = decorator.AdornerLayer;
if (layer != null)
{
var panel = new StackPanel
{
VerticalAlignment = VerticalAlignment.Top
};
InitGrowlPanel(panel);
SetIsCreatedAutomatically(panel, true);
var scrollViewer = new ScrollViewer
{
HorizontalAlignment = HorizontalAlignment.Right,
VerticalScrollBarVisibility = ScrollBarVisibility.Hidden,
IsInertiaEnabled = true,
IsPenetrating = true,
Content = panel
};
var container = new AdornerContainer(layer)
{
Child = scrollViewer
};
layer.Add(container);
return panel;
}
}
return null;
}
private static void RemoveDefaultPanel(Panel panel)
{
FrameworkElement element = WindowHelper.GetActiveWindow();
var decorator = VisualHelper.GetChild<AdornerDecorator>(element);
if (decorator != null)
{
var layer = decorator.AdornerLayer;
var adorner = VisualHelper.GetParent<Adorner>(panel);
if (adorner != null)
{
layer?.Remove(adorner);
}
}
}
private static void InitGrowlInfo(ref GrowlInfo growlInfo, InfoType infoType)
{
if (growlInfo == null) throw new ArgumentNullException(nameof(growlInfo));
@@ -487,18 +561,6 @@ namespace HandyControl.Controls
growlInfo.IconBrushKey = ResourceToken.PrimaryTextBrush;
growlInfo.StaysOpen = true;
growlInfo.ShowCloseButton = false;
Application.Current.Dispatcher?.Invoke(
#if NET40
new Action(
#endif
() =>
{
if (GrowlPanel.ContextMenu != null) GrowlPanel.ContextMenu.Opacity = 0;
}
#if NET40
)
#endif
);
}
else
{
@@ -769,7 +831,7 @@ namespace HandyControl.Controls
ShowGlobal(growlInfo);
}
private void ButtonClose_OnClick(object sender, RoutedEventArgs e) => Close();
private void ButtonClose_OnClick(object sender, RoutedEventArgs e) => Close(true, false);
/// <summary>
/// 关闭
@@ -784,17 +846,29 @@ namespace HandyControl.Controls
_timerClose?.Stop();
var transform = new TranslateTransform();
_gridMain.RenderTransform = transform;
var animation = AnimationHelper.CreateAnimation(ActualWidth);
var animation = AnimationHelper.CreateAnimation(FlowDirection == FlowDirection.LeftToRight ? ActualWidth : -ActualWidth);
animation.Completed += (s, e) =>
{
if (Parent is Panel panel)
{
panel.Children.Remove(this);
if (GrowlWindow?.GrowlPanel != null && GrowlWindow.GrowlPanel.Children.Count == 0)
if (GrowlWindow != null)
{
GrowlWindow.Close();
GrowlWindow = null;
if (GrowlWindow.GrowlPanel != null && GrowlWindow.GrowlPanel.Children.Count == 0)
{
GrowlWindow.Close();
GrowlWindow = null;
}
}
else
{
if (GrowlPanel != null && GrowlPanel.Children.Count == 0 && GetIsCreatedAutomatically(GrowlPanel))
{
// If the count of children is zero, we need to remove the panel, provided that the panel was created automatically
RemoveDefaultPanel(GrowlPanel);
GrowlPanel = null;
}
}
}
};
@@ -824,16 +898,7 @@ namespace HandyControl.Controls
/// 清除
/// </summary>
/// <param name="panel"></param>
private static void Clear(Panel panel)
{
if (panel == null) return;
panel.Children.Clear();
if (panel.ContextMenu != null)
{
panel.ContextMenu.IsOpen = false;
panel.ContextMenu.Opacity = 1;
}
}
private static void Clear(Panel panel) => panel?.Children.Clear();
/// <summary>
/// 清除
@@ -17,8 +17,7 @@ namespace HandyControl.Controls
GrowlPanel = new StackPanel
{
VerticalAlignment = VerticalAlignment.Top,
Margin = new Thickness(0, 10, 10, 10)
VerticalAlignment = VerticalAlignment.Top
};
Content = new ScrollViewer
@@ -19,9 +19,9 @@ namespace HandyControl.Controls
{
public class GifImage : Image, IDisposable
{
private static readonly Guid GifGuid = new Guid("{b96b3caa-0728-11d3-9d7b-0000f81ef32e}");
private static readonly Guid GifGuid = new("{b96b3caa-0728-11d3-9d7b-0000f81ef32e}");
private static readonly Guid GifSingleFrameGuid = new Guid("{b96b3cb0-0728-11d3-9d7b-0000f81ef32e}");
private static readonly Guid GifSingleFrameGuid = new("{b96b3cb0-0728-11d3-9d7b-0000f81ef32e}");
internal IntPtr NativeImage;
@@ -48,7 +48,7 @@ namespace HandyControl.Controls
/// <summary>
/// 图片保存对话框
/// </summary>
private static readonly SaveFileDialog SaveFileDialog = new SaveFileDialog
private static readonly SaveFileDialog SaveFileDialog = new()
{
Filter = $"{Lang.PngImg}|*.png"
};
@@ -160,6 +160,8 @@ namespace HandyControl.Controls
private DispatcherTimer _dispatcher;
private bool _isLoaded;
#endregion Data
#region ctor
@@ -174,7 +176,11 @@ namespace HandyControl.Controls
CommandBindings.Add(new CommandBinding(ControlCommands.RotateLeft, ButtonRotateLeft_OnClick));
CommandBindings.Add(new CommandBinding(ControlCommands.RotateRight, ButtonRotateRight_OnClick));
Loaded += (s, e) => Init();
Loaded += (s, e) =>
{
_isLoaded = true;
Init();
};
}
/// <summary>
@@ -445,7 +451,7 @@ namespace HandyControl.Controls
/// </summary>
private void Init()
{
if (ImageSource == null || !IsLoaded) return;
if (ImageSource == null || !_isLoaded) return;
if (ImageSource.IsDownloading)
{
@@ -464,13 +470,13 @@ namespace HandyControl.Controls
if (!_isOblique)
{
width = ImageSource.Width;
height = ImageSource.Height;
width = ImageSource.PixelWidth;
height = ImageSource.PixelHeight;
}
else
{
width = ImageSource.Height;
height = ImageSource.Width;
width = ImageSource.PixelHeight;
height = ImageSource.PixelWidth;
}
ImageWidth = width;
@@ -514,7 +520,7 @@ namespace HandyControl.Controls
{
if (_dispatcher == null) return;
if (ImageSource == null || !IsLoaded)
if (ImageSource == null || !_isLoaded)
{
_dispatcher.Stop();
_dispatcher.Tick -= Dispatcher_Tick;
@@ -116,7 +116,15 @@ namespace HandyControl.Controls
public CheckComboBox()
{
AddHandler(Controls.Tag.ClosedEvent, new RoutedEventHandler(Tags_OnClosed));
CommandBindings.Add(new CommandBinding(ControlCommands.Clear, (s, e) => SelectedItems.Clear()));
CommandBindings.Add(new CommandBinding(ControlCommands.Clear, (s, e) =>
{
SetCurrentValue(SelectedValueProperty, null);
SetCurrentValue(SelectedItemProperty, null);
SetCurrentValue(SelectedIndexProperty, -1);
SelectedItems.Clear();
}));
ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;
}
@@ -200,7 +208,7 @@ namespace HandyControl.Controls
private void Tags_OnClosed(object sender, RoutedEventArgs e)
{
if (e.OriginalSource is Tag tag && tag.Tag is CheckComboBoxItem checkComboBoxItem)
if (e.OriginalSource is Tag { Tag: CheckComboBoxItem checkComboBoxItem })
{
checkComboBoxItem.SetCurrentValue(IsSelectedProperty, false);
}
@@ -132,7 +132,13 @@ namespace HandyControl.Controls
public static readonly DependencyProperty IsDropDownOpenProperty = DependencyProperty.Register(
"IsDropDownOpen", typeof(bool), typeof(DateTimePicker), new FrameworkPropertyMetadata(ValueBoxes.FalseBox, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsDropDownOpenChanged, OnCoerceIsDropDownOpen));
private static object OnCoerceIsDropDownOpen(DependencyObject d, object baseValue) => d is DateTimePicker dp && !dp.IsEnabled ? false : baseValue;
private static object OnCoerceIsDropDownOpen(DependencyObject d, object baseValue) =>
d is DateTimePicker
{
IsEnabled: false
}
? false
: baseValue;
private static void OnIsDropDownOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
@@ -172,7 +178,7 @@ namespace HandyControl.Controls
private static void OnSelectedDateTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is DateTimePicker dp)) return;
if (d is not DateTimePicker dp) return;
if (dp.SelectedDateTime.HasValue)
{
@@ -555,7 +561,7 @@ namespace HandyControl.Controls
private void PopupPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is Popup popup && !popup.StaysOpen)
if (sender is Popup { StaysOpen: false })
{
if (_dropDownButton?.InputHitTest(e.GetPosition(_dropDownButton)) != null)
{
@@ -302,21 +302,18 @@ namespace HandyControl.Controls
ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.SelectionOpacityProperty, new Binding(SelectionOpacityProperty.Name) { Source = this });
ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.CaretBrushProperty, new Binding(CaretBrushProperty.Name) { Source = this });
if (_password != null)
if (_password is { Length: > 0 })
{
if (_password.Length > 0)
var valuePtr = IntPtr.Zero;
try
{
var valuePtr = IntPtr.Zero;
try
{
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(_password);
ActualPasswordBox.Password = Marshal.PtrToStringUni(valuePtr) ?? throw new InvalidOperationException();
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
_password.Clear();
}
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(_password);
ActualPasswordBox.Password = Marshal.PtrToStringUni(valuePtr) ?? throw new InvalidOperationException();
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
_password.Clear();
}
}
}
@@ -142,7 +142,13 @@ namespace HandyControl.Controls
typeof(TimePicker),
new FrameworkPropertyMetadata(ValueBoxes.FalseBox, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsDropDownOpenChanged, OnCoerceIsDropDownOpen));
private static object OnCoerceIsDropDownOpen(DependencyObject d, object baseValue) => d is TimePicker dp && !dp.IsEnabled ? false : baseValue;
private static object OnCoerceIsDropDownOpen(DependencyObject d, object baseValue) =>
d is TimePicker
{
IsEnabled: false
}
? false
: baseValue;
private static void OnIsDropDownOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
@@ -183,7 +189,7 @@ namespace HandyControl.Controls
private static void OnSelectedTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is TimePicker dp)) return;
if (d is not TimePicker dp) return;
if (dp.SelectedTime.HasValue)
{
@@ -340,16 +346,14 @@ namespace HandyControl.Controls
private static void OnClockChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ctl = (TimePicker) d;
var oldClock = e.OldValue as ClockBase;
var newClock = e.NewValue as ClockBase;
if (oldClock != null)
if (e.OldValue is ClockBase oldClock)
{
oldClock.SelectedTimeChanged -= ctl.Clock_SelectedTimeChanged;
oldClock.Confirmed -= ctl.Clock_Confirmed;
}
if (newClock != null)
if (e.NewValue is ClockBase newClock)
{
newClock.ShowConfirmButton = true;
newClock.SelectedTimeChanged += ctl.Clock_SelectedTimeChanged;
@@ -589,7 +593,7 @@ namespace HandyControl.Controls
private void PopupPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is Popup popup && !popup.StaysOpen)
if (sender is Popup { StaysOpen: false })
{
if (_dropDownButton?.InputHitTest(e.GetPosition(_dropDownButton)) != null)
{
@@ -62,7 +62,7 @@ namespace HandyControl.Controls
"DotDelayTime", typeof(double), typeof(LoadingBase),
new FrameworkPropertyMetadata(80.0, FrameworkPropertyMetadataOptions.AffectsRender));
protected readonly Canvas PrivateCanvas = new Canvas
protected readonly Canvas PrivateCanvas = new()
{
ClipToBounds = true
};
@@ -12,19 +12,10 @@ namespace HandyControl.Controls
{
public class AnimationPath : Shape
{
/// <summary>
/// 故事板
/// </summary>
private Storyboard _storyboard;
/// <summary>
/// 路径长度
/// </summary>
private double _pathLength;
/// <summary>
/// 路径
/// </summary>
public static readonly DependencyProperty DataProperty = DependencyProperty.Register(nameof(Data),
typeof(Geometry), typeof(AnimationPath), new FrameworkPropertyMetadata(null,
OnPropertiesChanged));
@@ -37,9 +28,6 @@ namespace HandyControl.Controls
}
}
/// <summary>
/// 路径
/// </summary>
public Geometry Data
{
get => (Geometry) GetValue(DataProperty);
@@ -48,31 +36,19 @@ namespace HandyControl.Controls
protected override Geometry DefiningGeometry => Data ?? Geometry.Empty;
/// <summary>
/// 路径长度
/// </summary>
public static readonly DependencyProperty PathLengthProperty = DependencyProperty.Register(
"PathLength", typeof(double), typeof(AnimationPath), new FrameworkPropertyMetadata(ValueBoxes.Double0Box, OnPropertiesChanged));
/// <summary>
/// 路径长度
/// </summary>
public double PathLength
{
get => (double) GetValue(PathLengthProperty);
set => SetValue(PathLengthProperty, value);
}
/// <summary>
/// 动画间隔时间
/// </summary>
public static readonly DependencyProperty DurationProperty = DependencyProperty.Register(
"Duration", typeof(Duration), typeof(AnimationPath), new FrameworkPropertyMetadata(new Duration(TimeSpan.FromSeconds(2)),
OnPropertiesChanged));
/// <summary>
/// 动画间隔时间
/// </summary>
public Duration Duration
{
get => (Duration) GetValue(DurationProperty);
@@ -94,27 +70,31 @@ namespace HandyControl.Controls
}
}));
/// <summary>
/// 是否正在播放动画
/// </summary>
public bool IsPlaying
{
get => (bool) GetValue(IsPlayingProperty);
set => SetValue(IsPlayingProperty, ValueBoxes.BooleanBox(value));
}
public static readonly DependencyProperty RepeatBehaviorProperty = DependencyProperty.Register(
"RepeatBehavior", typeof(RepeatBehavior), typeof(AnimationPath), new PropertyMetadata(RepeatBehavior.Forever));
public static readonly DependencyProperty RepeatBehaviorProperty =
Timeline.RepeatBehaviorProperty.AddOwner(typeof(AnimationPath),
new PropertyMetadata(RepeatBehavior.Forever));
/// <summary>
/// 动画重复行为
/// </summary>
public RepeatBehavior RepeatBehavior
{
get => (RepeatBehavior) GetValue(RepeatBehaviorProperty);
set => SetValue(RepeatBehaviorProperty, value);
}
public static readonly DependencyProperty FillBehaviorProperty =
Timeline.FillBehaviorProperty.AddOwner(typeof(AnimationPath), new PropertyMetadata(FillBehavior.Stop));
public FillBehavior FillBehavior
{
get { return (FillBehavior) GetValue(FillBehaviorProperty); }
set { SetValue(FillBehaviorProperty, value); }
}
static AnimationPath()
{
StretchProperty.AddOwner(typeof(AnimationPath), new FrameworkPropertyMetadata(Stretch.Uniform,
@@ -126,25 +106,16 @@ namespace HandyControl.Controls
public AnimationPath() => Loaded += (s, e) => UpdatePath();
/// <summary>
/// 动画完成事件
/// </summary>
public static readonly RoutedEvent CompletedEvent =
EventManager.RegisterRoutedEvent("Completed", RoutingStrategy.Bubble,
typeof(EventHandler), typeof(AnimationPath));
/// <summary>
/// 动画完成事件
/// </summary>
public event EventHandler Completed
{
add => AddHandler(CompletedEvent, value);
remove => RemoveHandler(CompletedEvent, value);
}
/// <summary>
/// 更新路径
/// </summary>
private void UpdatePath()
{
if (!Duration.HasTimeSpan || !IsPlaying) return;
@@ -160,7 +131,6 @@ namespace HandyControl.Controls
_pathLength
});
//定义动画
if (_storyboard != null)
{
_storyboard.Stop();
@@ -168,25 +138,26 @@ namespace HandyControl.Controls
}
_storyboard = new Storyboard
{
RepeatBehavior = RepeatBehavior
RepeatBehavior = RepeatBehavior,
FillBehavior = FillBehavior
};
_storyboard.Completed += Storyboard_Completed;
var frames = new DoubleAnimationUsingKeyFrames();
//开始位置
var frame0 = new LinearDoubleKeyFrame
var frameIn = new LinearDoubleKeyFrame
{
Value = _pathLength,
KeyTime = KeyTime.FromTimeSpan(TimeSpan.Zero)
};
//结束位置
var frame1 = new LinearDoubleKeyFrame
frames.KeyFrames.Add(frameIn);
var frameOut = new LinearDoubleKeyFrame
{
Value = -_pathLength,
Value = FillBehavior == FillBehavior.Stop ? -_pathLength : 0,
KeyTime = KeyTime.FromTimeSpan(Duration.TimeSpan)
};
frames.KeyFrames.Add(frame0);
frames.KeyFrames.Add(frame1);
frames.KeyFrames.Add(frameOut);
Storyboard.SetTarget(frames, this);
Storyboard.SetTargetProperty(frames, new PropertyPath(StrokeDashOffsetProperty));
@@ -63,7 +63,14 @@ namespace HandyControl.Controls
}
public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register(
"Maximum", typeof(int), typeof(Badge), new PropertyMetadata(ValueBoxes.Int99Box, OnValueChanged));
"Maximum", typeof(int), typeof(Badge), new PropertyMetadata(ValueBoxes.Int99Box, OnMaximumChanged));
private static void OnMaximumChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ctl = (Badge) d;
var v = ctl.Value;
ctl.SetCurrentValue(TextProperty, v <= ctl.Maximum ? v.ToString() : $"{ctl.Maximum}+");
}
public int Maximum
{
@@ -134,9 +134,9 @@ namespace HandyControl.Controls
set => SetValue(BorderDashOffsetProperty, value);
}
private static Size ConvertThickness2Size(Thickness th) => new Size(th.Left + th.Right, th.Top + th.Bottom);
private static Size ConvertThickness2Size(Thickness th) => new(th.Left + th.Right, th.Top + th.Bottom);
private static Rect DeflateRect(Rect rt, Thickness thick) => new Rect(rt.Left + thick.Left,
private static Rect DeflateRect(Rect rt, Thickness thick) => new(rt.Left + thick.Left,
rt.Top + thick.Top,
Math.Max(0.0, rt.Width - thick.Left - thick.Right),
Math.Max(0.0, rt.Height - thick.Top - thick.Bottom));
@@ -28,7 +28,7 @@ namespace HandyControl.Controls
"ShowEmpty", typeof(bool), typeof(Empty), new FrameworkPropertyMetadata(ValueBoxes.FalseBox, FrameworkPropertyMetadataOptions.Inherits));
public static void SetShowEmpty(DependencyObject element, bool value)
=> element.SetValue(ShowEmptyProperty, value);
=> element.SetValue(ShowEmptyProperty, ValueBoxes.BooleanBox(value));
public static bool GetShowEmpty(DependencyObject element)
=> (bool) element.GetValue(ShowEmptyProperty);
@@ -45,7 +45,7 @@ namespace HandyControl.Controls
{
Stretch = Stretch.UniformToFill
}
: ResourceHelper.GetResource<Brush>("SecondaryRegionBrush");
: ResourceHelper.GetResourceInternal<Brush>("SecondaryRegionBrush");
}
public ImageSource Source
@@ -18,7 +18,7 @@ namespace HandyControl.Controls
private const string ElementVisualBrush = "PART_VisualBrush";
private VisualBrush _visualBrush = new VisualBrush();
private VisualBrush _visualBrush = new();
private readonly TranslateTransform _translateTransform;
@@ -40,7 +40,7 @@ namespace HandyControl.Controls
set => SetValue(VerticalOffsetProperty, value);
}
public static Magnifier Default => new Magnifier();
public static Magnifier Default => new();
public static readonly DependencyProperty ScaleProperty = DependencyProperty.Register(
"Scale", typeof(double), typeof(Magnifier), new PropertyMetadata(5.0, OnScaleChanged), ValidateHelper.IsInRangeOfPosDouble);
@@ -129,7 +129,7 @@ namespace HandyControl.Controls
{
layer.Remove(_adornerContainer);
}
else if (_adornerContainer != null && _adornerContainer.Parent is AdornerLayer parent)
else if (_adornerContainer is { Parent: AdornerLayer parent })
{
parent.Remove(_adornerContainer);
}
@@ -22,7 +22,7 @@ namespace HandyControl.Controls
private bool _added;
private readonly object _syncObj = new object();
private readonly object _syncObj = new();
private readonly int _id;
@@ -58,7 +58,7 @@ namespace HandyControl.Controls
private static int NextId;
private static readonly Dictionary<string, NotifyIcon> NotifyIconDic = new Dictionary<string, NotifyIcon>();
private static readonly Dictionary<string, NotifyIcon> NotifyIconDic = new();
static NotifyIcon()
{
@@ -192,21 +192,14 @@ namespace HandyControl.Controls
szInfo = content ?? string.Empty
};
switch (infoType)
data.dwInfoFlags = infoType switch
{
case NotifyIconInfoType.Info:
data.dwInfoFlags = InteropValues.NIIF_INFO;
break;
case NotifyIconInfoType.Warning:
data.dwInfoFlags = InteropValues.NIIF_WARNING;
break;
case NotifyIconInfoType.Error:
data.dwInfoFlags = InteropValues.NIIF_ERROR;
break;
case NotifyIconInfoType.None:
data.dwInfoFlags = InteropValues.NIIF_NONE;
break;
}
NotifyIconInfoType.Info => InteropValues.NIIF_INFO,
NotifyIconInfoType.Warning => InteropValues.NIIF_WARNING,
NotifyIconInfoType.Error => InteropValues.NIIF_ERROR,
NotifyIconInfoType.None => InteropValues.NIIF_NONE,
_ => data.dwInfoFlags
};
InteropMethods.Shell_NotifyIcon(InteropValues.NIM_MODIFY, data);
}
@@ -89,7 +89,7 @@ namespace HandyControl.Controls
/// 最大页数
/// </summary>
public static readonly DependencyProperty MaxPageCountProperty = DependencyProperty.Register(
"MaxPageCount", typeof(int), typeof(Pagination), new PropertyMetadata(ValueBoxes.Int1Box, OnMaxPageCountChanged, CoerceMaxPageCount), ValidateHelper.IsInRangeOfPosInt);
"MaxPageCount", typeof(int), typeof(Pagination), new PropertyMetadata(ValueBoxes.Int1Box, OnMaxPageCountChanged, CoerceMaxPageCount), ValidateHelper.IsInRangeOfPosIntIncludeZero);
private static object CoerceMaxPageCount(DependencyObject d, object basevalue)
{
@@ -157,11 +157,11 @@ namespace HandyControl.Controls
/// 当前页
/// </summary>
public static readonly DependencyProperty PageIndexProperty = DependencyProperty.Register(
"PageIndex", typeof(int), typeof(Pagination), new PropertyMetadata(ValueBoxes.Int1Box, OnPageIndexChanged, CoercePageIndex), ValidateHelper.IsInRangeOfPosInt);
"PageIndex", typeof(int), typeof(Pagination), new PropertyMetadata(ValueBoxes.Int1Box, OnPageIndexChanged, CoercePageIndex), ValidateHelper.IsInRangeOfPosIntIncludeZero);
private static object CoercePageIndex(DependencyObject d, object basevalue)
{
if (!(d is Pagination pagination)) return 1;
if (d is not Pagination pagination) return 1;
var intValue = (int) basevalue;
return intValue < 1
@@ -383,16 +383,16 @@ namespace HandyControl.Controls
private RadioButton CreateButton(int page)
{
return new RadioButton
return new()
{
Style = ResourceHelper.GetResource<Style>(ResourceToken.PaginationButtonStyle),
Style = ResourceHelper.GetResourceInternal<Style>(ResourceToken.PaginationButtonStyle),
Content = page.ToString()
};
}
private void ToggleButton_OnChecked(object sender, RoutedEventArgs e)
{
if (!(e.OriginalSource is RadioButton button)) return;
if (e.OriginalSource is not RadioButton button) return;
if (button.IsChecked == false) return;
PageIndex = int.Parse(button.Content.ToString());
}
@@ -148,7 +148,7 @@ namespace HandyControl.Controls
set => SetValue(IsOpenProperty, ValueBoxes.BooleanBox(value));
}
public static Poptip Default => new Poptip();
public static Poptip Default => new();
protected sealed override void OnTargetChanged(FrameworkElement element, bool isNew)
{
@@ -287,7 +287,7 @@ namespace HandyControl.Controls
private void Element_MouseEnter(object sender, MouseEventArgs e)
{
var hitMode = GetIsInstance(Target) ? HitMode : GetHitMode(Target);
if (hitMode != HitMode.Hover || hitMode == HitMode.None) return;
if (hitMode != HitMode.Hover) return;
SwitchPoptip(true);
}
@@ -295,7 +295,7 @@ namespace HandyControl.Controls
private void Element_MouseLeave(object sender, MouseEventArgs e)
{
var hitMode = GetIsInstance(Target) ? HitMode : GetHitMode(Target);
if (hitMode != HitMode.Hover || hitMode == HitMode.None) return;
if (hitMode != HitMode.Hover) return;
SwitchPoptip(false);
}
@@ -303,7 +303,7 @@ namespace HandyControl.Controls
private void Element_GotFocus(object sender, RoutedEventArgs e)
{
var hitMode = GetIsInstance(Target) ? HitMode : GetHitMode(Target);
if (hitMode != HitMode.Focus || hitMode == HitMode.None) return;
if (hitMode != HitMode.Focus) return;
SwitchPoptip(true);
}
@@ -311,7 +311,7 @@ namespace HandyControl.Controls
private void Element_LostFocus(object sender, RoutedEventArgs e)
{
var hitMode = GetIsInstance(Target) ? HitMode : GetHitMode(Target);
if (hitMode != HitMode.Focus || hitMode == HitMode.None) return;
if (hitMode != HitMode.Focus) return;
SwitchPoptip(false);
}
@@ -11,10 +11,14 @@ namespace HandyControl.Controls
{
private FrameworkElement _contentPresenter;
private static Storyboard StoryboardBuildInDefault;
private Storyboard _storyboardBuildIn;
public TransitioningContentControl()
{
Loaded += TransitioningContentControl_Loaded;
IsVisibleChanged += TransitioningContentControl_IsVisibleChanged;
Unloaded += TransitioningContentControl_Unloaded;
}
public static readonly DependencyProperty TransitionModeProperty = DependencyProperty.Register(
@@ -23,7 +27,13 @@ namespace HandyControl.Controls
private static void OnTransitionModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ctl = (TransitioningContentControl) d;
ctl.StartTransition();
ctl.OnTransitionModeChanged((TransitionMode) e.NewValue);
}
private void OnTransitionModeChanged(TransitionMode newValue)
{
_storyboardBuildIn = ResourceHelper.GetResourceInternal<Storyboard>($"{newValue}Transition");
StartTransition();
}
public TransitionMode TransitionMode
@@ -43,19 +53,33 @@ namespace HandyControl.Controls
private void TransitioningContentControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) => StartTransition();
private void TransitioningContentControl_Loaded(object sender, RoutedEventArgs e) => StartTransition();
private void TransitioningContentControl_Loaded(object sender, RoutedEventArgs e)
{
StartTransition();
IsVisibleChanged += TransitioningContentControl_IsVisibleChanged;
}
private void TransitioningContentControl_Unloaded(object sender, RoutedEventArgs e)
{
IsVisibleChanged -= TransitioningContentControl_IsVisibleChanged;
}
private void StartTransition()
{
if (Visibility != Visibility.Visible || _contentPresenter == null) return;
if (!IsArrangeValid || _contentPresenter == null) return;
if (TransitionStoryboard != null)
{
TransitionStoryboard.Begin(_contentPresenter);
}
else if (Application.Current != null)
else if (_storyboardBuildIn != null)
{
ResourceHelper.GetResource<Storyboard>($"{TransitionMode.ToString()}Transition")?.Begin(_contentPresenter);
_storyboardBuildIn?.Begin(_contentPresenter);
}
else
{
StoryboardBuildInDefault ??= ResourceHelper.GetResourceInternal<Storyboard>($"{default(TransitionMode)}Transition");
StoryboardBuildInDefault?.Begin(_contentPresenter);
}
}
@@ -0,0 +1,120 @@
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using HandyControl.Tools;
namespace HandyControl.Controls
{
public class ElementGroup : SimpleStackPanel
{
private static readonly Dictionary<Orientation, Dictionary<ChildLocation, CornerRadius>> CornerRadiusDict;
static ElementGroup()
{
var defaultCornerRadius = ResourceHelper.GetResourceInternal<CornerRadius>("DefaultCornerRadius");
CornerRadiusDict = new Dictionary<Orientation, Dictionary<ChildLocation, CornerRadius>>
{
[Orientation.Horizontal] = new()
{
[ChildLocation.Single] = defaultCornerRadius,
[ChildLocation.First] = new CornerRadius(defaultCornerRadius.TopLeft, 0, 0, defaultCornerRadius.BottomLeft),
[ChildLocation.Middle] = new CornerRadius(),
[ChildLocation.Last] = new CornerRadius(0, defaultCornerRadius.TopRight, defaultCornerRadius.BottomRight, 0)
},
[Orientation.Vertical] = new()
{
[ChildLocation.Single] = defaultCornerRadius,
[ChildLocation.First] = new CornerRadius(defaultCornerRadius.TopLeft, defaultCornerRadius.TopRight, 0, 0),
[ChildLocation.Middle] = new CornerRadius(),
[ChildLocation.Last] = new CornerRadius(0, 0, defaultCornerRadius.BottomRight, defaultCornerRadius.BottomLeft)
}
};
}
protected override void OnVisualChildrenChanged(DependencyObject visualAdded, DependencyObject visualRemoved)
{
base.OnVisualChildrenChanged(visualAdded, visualRemoved);
if (visualAdded is UIElement elementAdded)
{
elementAdded.GotFocus += ElementAdded_GotFocus;
elementAdded.LostFocus += ElementAdded_LostFocus;
}
if (visualRemoved is UIElement elementRemoved)
{
elementRemoved.GotFocus -= ElementAdded_GotFocus;
elementRemoved.LostFocus -= ElementAdded_LostFocus;
}
var childrenCount = InternalChildren.Count;
if (childrenCount == 0)
{
return;
}
var orientation = Orientation;
if (childrenCount == 1)
{
UpdateChildCornerRadius(InternalChildren[0], CornerRadiusDict[orientation][ChildLocation.Single]);
}
else
{
UpdateChildCornerRadius(InternalChildren[0], CornerRadiusDict[orientation][ChildLocation.First]);
var childMargin = orientation == Orientation.Horizontal
? new Thickness(-1, 0, 0, 0)
: new Thickness(0, -1, 0, 0);
for (var childIndex = 1; childIndex < childrenCount; childIndex++)
{
var child = InternalChildren[childIndex];
child.SetCurrentValue(MarginProperty, childMargin);
UpdateChildCornerRadius(child, CornerRadiusDict[orientation][ChildLocation.Middle]);
}
var lastChild = InternalChildren[childrenCount - 1];
lastChild.SetCurrentValue(MarginProperty, childMargin);
UpdateChildCornerRadius(lastChild, CornerRadiusDict[orientation][ChildLocation.Last]);
}
}
private static void UpdateChildCornerRadius(DependencyObject child, CornerRadius cornerRadius)
{
if (child is Border border)
{
border.SetCurrentValue(Border.CornerRadiusProperty, cornerRadius);
}
else
{
BorderElement.SetCornerRadius(child, cornerRadius);
}
}
private void ElementAdded_LostFocus(object sender, RoutedEventArgs e)
{
if (sender is UIElement element)
{
SetZIndex(element, 0);
}
}
private void ElementAdded_GotFocus(object sender, RoutedEventArgs e)
{
if (sender is UIElement element)
{
SetZIndex(element, int.MaxValue);
}
}
private enum ChildLocation
{
Single,
First,
Middle,
Last
}
}
}
@@ -16,7 +16,7 @@ namespace HandyControl.Controls
private int _lineCount;
private readonly List<FlexItemInfo> _orderList = new List<FlexItemInfo>();
private readonly List<FlexItemInfo> _orderList = new();
#region Item
@@ -193,7 +193,7 @@ namespace HandyControl.Controls
curLineSize = sz;
_lineCount++;
if (MathHelper.GreaterThan(sz.U, _uvConstraint.U)) //the element is wider then the constrint - give it a separate line
if (MathHelper.GreaterThan(sz.U, _uvConstraint.U)) //the element is wider then the constrint - give it a separate line
{
panelSize.U = Math.Max(sz.U, panelSize.U);
panelSize.V += sz.V;
@@ -260,7 +260,7 @@ namespace HandyControl.Controls
lineIndex++;
curLineSizeArr[lineIndex] = sz;
if (MathHelper.GreaterThan(sz.U, uvFinalSize.U)) //the element is wider then the constraint - give it a separate line
if (MathHelper.GreaterThan(sz.U, uvFinalSize.U)) //the element is wider then the constraint - give it a separate line
{
//switch to next line which only contain one element
lastInLineArr[lineIndex] = i;
@@ -399,7 +399,7 @@ namespace HandyControl.Controls
lineIndex++;
itemsU = 0;
if (i >= lastInLineArr[lineIndex]) //the element is wider then the constraint - give it a separate line
if (i >= lastInLineArr[lineIndex]) //the element is wider then the constraint - give it a separate line
{
//switch to next line which only contain one element
ArrangeLine(new FlexLineInfo
@@ -507,7 +507,7 @@ namespace HandyControl.Controls
{
flexGrowItem = constraintFreeU / flexGrowSum;
lineInfo.ScaleU = 1;
lineFreeU = 0; //line free U was used up
lineFreeU = 0; //line free U was used up
}
for (var i = 0; i < itemCount; i++)
@@ -543,7 +543,7 @@ namespace HandyControl.Controls
{
flexShrinkItem = constraintFreeU / flexShrinkSum;
lineInfo.ScaleU = 1;
lineFreeU = 0; //line free U was used up
lineFreeU = 0; //line free U was used up
}
for (var i = 0; i < itemCount; i++)
@@ -648,7 +648,12 @@ namespace HandyControl.Controls
public int Index { get; }
public int CompareTo(FlexItemInfo other) => Order.CompareTo(other.Order);
public int CompareTo(FlexItemInfo other)
{
var orderCompare = Order.CompareTo(other.Order);
if (orderCompare != 0) return orderCompare;
return Index.CompareTo(other.Index);
}
}
private struct FlexLineInfo
@@ -32,7 +32,7 @@ namespace HandyControl.Controls
private static bool OnSpanValidate(object value)
{
var v = (int) value;
return v >= 1 && v <= 24;
return v is >= 1 and <= 24;
}
public int Span
@@ -84,7 +84,7 @@ namespace HandyControl.Controls
return double.IsNaN(v) || v >= 0.0d && !double.IsPositiveInfinity(v);
}
private void ArrangeLine(double v, double lineV, int start, int end, bool useItemU, double itemU, double spacing)
private void ArrangeWrapLine(double v, double lineV, int start, int end, bool useItemU, double itemU, double spacing)
{
double u = 0;
var isHorizontal = _orientation == Orientation.Horizontal;
@@ -104,6 +104,26 @@ namespace HandyControl.Controls
}
}
private void ArrangeLine(double lineV, bool useItemU, double itemU, double spacing)
{
double u = 0;
var isHorizontal = _orientation == Orientation.Horizontal;
var children = InternalChildren;
for (var i = 0; i < children.Count; i++)
{
var child = children[i];
if (child == null) continue;
var childSize = new UVSize(_orientation, child.DesiredSize.Width, child.DesiredSize.Height);
var layoutSlotU = useItemU ? itemU : childSize.U;
child.Arrange(isHorizontal ? new Rect(u, 0, layoutSlotU, lineV) : new Rect(0, u, lineV, layoutSlotU));
u += layoutSlotU + spacing;
}
}
protected override Size MeasureOverride(Size constraint)
{
var curLineSize = new UVSize(_orientation);
@@ -123,35 +143,69 @@ namespace HandyControl.Controls
var children = InternalChildren;
var isFirst = true;
for (int i = 0, count = children.Count; i < count; i++)
if (childWrapping == VisualWrapping.Wrap)
{
var child = children[i];
if (child == null) continue;
child.Measure(childConstraint);
var sz = new UVSize(
_orientation,
itemWidthSet ? itemWidth : child.DesiredSize.Width,
itemHeightSet ? itemHeight : child.DesiredSize.Height);
if (childWrapping == VisualWrapping.Wrap && MathHelper.GreaterThan(curLineSize.U + sz.U + spacing, uvConstraint.U))
for (int i = 0, count = children.Count; i < count; i++)
{
panelSize.U = Math.Max(curLineSize.U, panelSize.U);
panelSize.V += curLineSize.V + spacing;
curLineSize = sz;
var child = children[i];
if (child == null) continue;
if (MathHelper.GreaterThan(sz.U, uvConstraint.U))
child.Measure(childConstraint);
var sz = new UVSize(
_orientation,
itemWidthSet ? itemWidth : child.DesiredSize.Width,
itemHeightSet ? itemHeight : child.DesiredSize.Height);
if (MathHelper.GreaterThan(curLineSize.U + sz.U + spacing, uvConstraint.U))
{
panelSize.U = Math.Max(sz.U, panelSize.U);
panelSize.V += sz.V + spacing;
curLineSize = new UVSize(_orientation);
}
panelSize.U = Math.Max(curLineSize.U, panelSize.U);
panelSize.V += curLineSize.V + spacing;
curLineSize = sz;
isFirst = true;
if (MathHelper.GreaterThan(sz.U, uvConstraint.U))
{
panelSize.U = Math.Max(sz.U, panelSize.U);
panelSize.V += sz.V + spacing;
curLineSize = new UVSize(_orientation);
}
isFirst = true;
}
else
{
curLineSize.U += isFirst ? sz.U : sz.U + spacing;
curLineSize.V = Math.Max(sz.V, curLineSize.V);
isFirst = false;
}
}
}
else
{
var layoutSlotSize = constraint;
if (_orientation == Orientation.Horizontal)
{
layoutSlotSize.Width = double.PositiveInfinity;
}
else
{
layoutSlotSize.Height = double.PositiveInfinity;
}
for (int i = 0, count = children.Count; i < count; ++i)
{
var child = children[i];
if (child == null) continue;
child.Measure(layoutSlotSize);
var sz = new UVSize(
_orientation,
itemWidthSet ? itemWidth : child.DesiredSize.Width,
itemHeightSet ? itemHeight : child.DesiredSize.Height);
curLineSize.U += isFirst ? sz.U : sz.U + spacing;
curLineSize.V = Math.Max(sz.V, curLineSize.V);
@@ -183,46 +237,53 @@ namespace HandyControl.Controls
var children = InternalChildren;
var isFirst = true;
for (int i = 0, count = children.Count; i < count; i++)
if (childWrapping == VisualWrapping.Wrap)
{
var child = children[i];
if (child == null) continue;
var sz = new UVSize(
_orientation,
itemWidthSet ? itemWidth : child.DesiredSize.Width,
itemHeightSet ? itemHeight : child.DesiredSize.Height);
if (childWrapping == VisualWrapping.Wrap && MathHelper.GreaterThan(curLineSize.U + sz.U + spacing, uvFinalSize.U))
for (int i = 0, count = children.Count; i < count; i++)
{
ArrangeLine(accumulatedV, curLineSize.V, firstInLine, i, useItemU, itemU, spacing);
var child = children[i];
if (child == null) continue;
accumulatedV += curLineSize.V + spacing;
curLineSize = sz;
var sz = new UVSize(
_orientation,
itemWidthSet ? itemWidth : child.DesiredSize.Width,
itemHeightSet ? itemHeight : child.DesiredSize.Height);
if (MathHelper.GreaterThan(sz.U, uvFinalSize.U))
if (MathHelper.GreaterThan(curLineSize.U + sz.U + spacing, uvFinalSize.U))
{
ArrangeLine(accumulatedV, sz.V, i, ++i, useItemU, itemU, spacing);
ArrangeWrapLine(accumulatedV, curLineSize.V, firstInLine, i, useItemU, itemU, spacing);
accumulatedV += sz.V + spacing;
curLineSize = new UVSize(_orientation);
accumulatedV += curLineSize.V + spacing;
curLineSize = sz;
if (MathHelper.GreaterThan(sz.U, uvFinalSize.U))
{
ArrangeWrapLine(accumulatedV, sz.V, i, ++i, useItemU, itemU, spacing);
accumulatedV += sz.V + spacing;
curLineSize = new UVSize(_orientation);
}
firstInLine = i;
isFirst = true;
}
else
{
curLineSize.U += isFirst ? sz.U : sz.U + spacing;
curLineSize.V = Math.Max(sz.V, curLineSize.V);
firstInLine = i;
isFirst = true;
isFirst = false;
}
}
else
{
curLineSize.U += isFirst ? sz.U : sz.U + spacing;
curLineSize.V = Math.Max(sz.V, curLineSize.V);
isFirst = false;
if (firstInLine < children.Count)
{
ArrangeWrapLine(accumulatedV, curLineSize.V, firstInLine, children.Count, useItemU, itemU, spacing);
}
}
if (firstInLine < children.Count)
else
{
ArrangeLine(accumulatedV, curLineSize.V, firstInLine, children.Count, useItemU, itemU, spacing);
ArrangeLine(uvFinalSize.V, useItemU, itemU, spacing);
}
return finalSize;
@@ -14,9 +14,9 @@ namespace HandyControl.Controls
{
public override FrameworkElement CreateElement(PropertyItem propertyItem) => new System.Windows.Controls.ComboBox
{
Style = ResourceHelper.GetResource<Style>("ComboBoxCapsule"),
Style = ResourceHelper.GetResourceInternal<Style>("ComboBoxCapsule"),
ItemsSource = Enum.GetValues(propertyItem.PropertyType),
ItemTemplateSelector = ResourceHelper.GetResource<DataTemplateSelector>("HorizontalAlignmentPathTemplateSelector"),
ItemTemplateSelector = ResourceHelper.GetResourceInternal<DataTemplateSelector>("HorizontalAlignmentPathTemplateSelector"),
HorizontalAlignment = HorizontalAlignment.Left
};
@@ -48,16 +48,16 @@ namespace HandyControl.Controls
switch (horizontalAlignment)
{
case HorizontalAlignment.Left:
factory.SetValue(Path.DataProperty, ResourceHelper.GetResource<Geometry>("AlignLeftGeometry"));
factory.SetValue(Path.DataProperty, ResourceHelper.GetResourceInternal<Geometry>("AlignLeftGeometry"));
break;
case HorizontalAlignment.Center:
factory.SetValue(Path.DataProperty, ResourceHelper.GetResource<Geometry>("AlignHCenterGeometry"));
factory.SetValue(Path.DataProperty, ResourceHelper.GetResourceInternal<Geometry>("AlignHCenterGeometry"));
break;
case HorizontalAlignment.Right:
factory.SetValue(Path.DataProperty, ResourceHelper.GetResource<Geometry>("AlignRightGeometry"));
factory.SetValue(Path.DataProperty, ResourceHelper.GetResourceInternal<Geometry>("AlignRightGeometry"));
break;
case HorizontalAlignment.Stretch:
factory.SetValue(Path.DataProperty, ResourceHelper.GetResource<Geometry>("AlignHStretchGeometry"));
factory.SetValue(Path.DataProperty, ResourceHelper.GetResourceInternal<Geometry>("AlignHStretchGeometry"));
break;
}
@@ -15,6 +15,6 @@ namespace HandyControl.Controls
public override BindingMode GetBindingMode(PropertyItem propertyItem) => BindingMode.OneWay;
protected override IValueConverter GetConverter(PropertyItem propertyItem) => ResourceHelper.GetResource<IValueConverter>("Object2StringConverter");
protected override IValueConverter GetConverter(PropertyItem propertyItem) => ResourceHelper.GetResourceInternal<IValueConverter>("Object2StringConverter");
}
}
@@ -8,7 +8,7 @@ namespace HandyControl.Controls
{
public override FrameworkElement CreateElement(PropertyItem propertyItem) => new ToggleButton
{
Style = ResourceHelper.GetResource<Style>("ToggleButtonSwitch"),
Style = ResourceHelper.GetResourceInternal<Style>("ToggleButtonSwitch"),
HorizontalAlignment = HorizontalAlignment.Left,
IsEnabled = !propertyItem.IsReadOnly
};
@@ -14,9 +14,9 @@ namespace HandyControl.Controls
{
public override FrameworkElement CreateElement(PropertyItem propertyItem) => new System.Windows.Controls.ComboBox
{
Style = ResourceHelper.GetResource<Style>("ComboBoxCapsule"),
Style = ResourceHelper.GetResourceInternal<Style>("ComboBoxCapsule"),
ItemsSource = Enum.GetValues(propertyItem.PropertyType),
ItemTemplateSelector = ResourceHelper.GetResource<DataTemplateSelector>("VerticalAlignmentPathTemplateSelector"),
ItemTemplateSelector = ResourceHelper.GetResourceInternal<DataTemplateSelector>("VerticalAlignmentPathTemplateSelector"),
HorizontalAlignment = HorizontalAlignment.Left
};
@@ -48,16 +48,16 @@ namespace HandyControl.Controls
switch (verticalAlignment)
{
case VerticalAlignment.Top:
factory.SetValue(Path.DataProperty, ResourceHelper.GetResource<Geometry>("AlignTopGeometry"));
factory.SetValue(Path.DataProperty, ResourceHelper.GetResourceInternal<Geometry>("AlignTopGeometry"));
break;
case VerticalAlignment.Center:
factory.SetValue(Path.DataProperty, ResourceHelper.GetResource<Geometry>("AlignVCenterGeometry"));
factory.SetValue(Path.DataProperty, ResourceHelper.GetResourceInternal<Geometry>("AlignVCenterGeometry"));
break;
case VerticalAlignment.Bottom:
factory.SetValue(Path.DataProperty, ResourceHelper.GetResource<Geometry>("AlignBottomGeometry"));
factory.SetValue(Path.DataProperty, ResourceHelper.GetResourceInternal<Geometry>("AlignBottomGeometry"));
break;
case VerticalAlignment.Stretch:
factory.SetValue(Path.DataProperty, ResourceHelper.GetResource<Geometry>("AlignVStretchGeometry"));
factory.SetValue(Path.DataProperty, ResourceHelper.GetResourceInternal<Geometry>("AlignVStretchGeometry"));
break;
}
@@ -33,7 +33,7 @@ namespace HandyControl.Controls
CommandBindings.Add(new CommandBinding(ControlCommands.SortByName, SortByName, (s, e) => e.CanExecute = ShowSortButton));
}
public virtual PropertyResolver PropertyResolver { get; } = new PropertyResolver();
public virtual PropertyResolver PropertyResolver { get; } = new();
public static readonly RoutedEvent SelectedObjectChangedEvent =
EventManager.RegisterRoutedEvent("SelectedObjectChanged", RoutingStrategy.Bubble,
@@ -181,7 +181,7 @@ namespace HandyControl.Controls
}
}
protected virtual PropertyItem CreatePropertyItem(PropertyDescriptor propertyDescriptor) => new PropertyItem
protected virtual PropertyItem CreatePropertyItem(PropertyDescriptor propertyDescriptor) => new()
{
Category = PropertyResolver.ResolveCategory(propertyDescriptor),
DisplayName = PropertyResolver.ResolveDisplayName(propertyDescriptor),
@@ -10,7 +10,7 @@ namespace HandyControl.Controls
{
public class PropertyResolver
{
private static readonly Dictionary<Type, EditorTypeCode> TypeCodeDic = new Dictionary<Type, EditorTypeCode>
private static readonly Dictionary<Type, EditorTypeCode> TypeCodeDic = new()
{
[typeof(string)] = EditorTypeCode.PlainText,
[typeof(sbyte)] = EditorTypeCode.SByteNumber,
@@ -99,10 +99,10 @@ namespace HandyControl.Controls
_ => new ReadOnlyTextPropertyEditor()
}
: type.IsSubclassOf(typeof(Enum))
? (PropertyEditorBase) new EnumPropertyEditor()
? new EnumPropertyEditor()
: new ReadOnlyTextPropertyEditor();
public virtual PropertyEditorBase CreateEditor(Type type) => new ReadOnlyTextPropertyEditor();
public virtual PropertyEditorBase CreateEditor(Type type) => Activator.CreateInstance(type) as PropertyEditorBase ?? new ReadOnlyTextPropertyEditor();
private enum EditorTypeCode
{
@@ -33,7 +33,7 @@ namespace HandyControl.Controls
private BitmapSource _imageSource;
private static readonly Guid BmpGuid = new Guid("{b96b3cab-0728-11d3-9d7b-0000f81ef32e}");
private static readonly Guid BmpGuid = new("{b96b3cab-0728-11d3-9d7b-0000f81ef32e}");
#region const
@@ -188,7 +188,7 @@ namespace HandyControl.Controls
public ScreenshotWindow(Screenshot screenshot)
{
Style = ResourceHelper.GetResource<Style>(ResourceToken.Window4ScreenshotStyle);
Style = ResourceHelper.GetResourceInternal<Style>(ResourceToken.Window4ScreenshotStyle);
_screenshot = screenshot;
DataContext = this;
@@ -149,7 +149,7 @@ namespace HandyControl.Controls
if (Role == SideMenuItemRole.Header && ItemsHost.Children.Count > 0)
{
var item = ItemsHost.Children.OfType<SideMenuItem>().FirstOrDefault();
if (item != null && !item.IsSelected)
if (item is { IsSelected: false })
{
item.OnSelected(new RoutedEventArgs(SelectedEvent, item));
}
@@ -165,7 +165,7 @@ namespace HandyControl.Controls
{
layer.Remove(_adorner);
}
else if (_adorner != null && _adorner.Parent is AdornerLayer parent)
else if (_adorner is { Parent: AdornerLayer parent })
{
parent.Remove(_adorner);
}
@@ -248,7 +248,7 @@ namespace HandyControl.Controls
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (IsMoveToPointEnabled && _track.ThumbStart != null && !_track.ThumbStart.IsMouseOver && _track.ThumbEnd != null && !_track.ThumbEnd.IsMouseOver)
if (IsMoveToPointEnabled && _track.ThumbStart is { IsMouseOver: false } && _track.ThumbEnd is { IsMouseOver: false })
{
// Here we need to determine whether it's closer to the starting point or the end point.
var pt = e.MouseDevice.GetPosition(_track);
@@ -301,7 +301,7 @@ namespace HandyControl.Controls
{
// If ticks collection is available, use it.
// Note that ticks may be unsorted.
if (Ticks != null && Ticks.Count > 0)
if (Ticks is { Count: > 0 })
{
foreach (var tick in Ticks)
{
@@ -341,7 +341,7 @@ namespace HandyControl.Controls
var previous = Minimum;
var next = Maximum;
if (Ticks != null && Ticks.Count > 0)
if (Ticks is { Count: > 0 })
{
foreach (var tick in Ticks)
{
@@ -429,7 +429,7 @@ namespace HandyControl.Controls
{
// Show AutoToolTip if needed.
if (!(e.OriginalSource is RangeThumb thumb)) return;
if (e.OriginalSource is not RangeThumb thumb) return;
_thumbCurrent = thumb;
_originThumbPoint = Mouse.GetPosition(_thumbCurrent);
_thumbCurrent.StartDrag();
@@ -531,7 +531,7 @@ namespace HandyControl.Controls
protected virtual void OnThumbDragDelta(DragDeltaEventArgs e)
{
if (!(e.OriginalSource is Thumb thumb)) return;
if (e.OriginalSource is not Thumb thumb) return;
var isStart = thumb.Equals(_track.ThumbStart);
if (!isStart)
{
@@ -579,7 +579,7 @@ namespace HandyControl.Controls
{
// Show AutoToolTip if needed.
if (!(e.OriginalSource is Thumb thumb) || AutoToolTipPlacement == AutoToolTipPlacement.None)
if (e.OriginalSource is not Thumb thumb || AutoToolTipPlacement == AutoToolTipPlacement.None)
{
return;
}
@@ -397,10 +397,7 @@ namespace HandyControl.Controls
{
if (oldValue != newValue)
{
if (_visualChildren == null)
{
_visualChildren = new Visual[5];
}
_visualChildren ??= new Visual[5];
if (oldValue != null)
{
@@ -236,7 +236,7 @@ namespace HandyControl.Controls
{
for (var i = 0; i < Items.Count; i++)
{
if (!(ItemContainerGenerator.ContainerFromIndex(i) is TabItem item)) return;
if (ItemContainerGenerator.ContainerFromIndex(i) is not TabItem item) return;
item.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
item.TabPanel = HeaderPanel;
}
@@ -321,7 +321,7 @@ namespace HandyControl.Controls
_buttonOverflow.Menu.Items.Clear();
for (var i = 0; i < Items.Count; i++)
{
if (!(ItemContainerGenerator.ContainerFromIndex(i) is TabItem item)) continue;
if (ItemContainerGenerator.ContainerFromIndex(i) is not TabItem item) continue;
var menuItem = new MenuItem
{
@@ -350,14 +350,10 @@ namespace HandyControl.Controls
{
list.Remove(actualItem);
list.Insert(0, actualItem);
if (IsAnimationEnabled)
{
HeaderPanel.SetValue(TabPanel.FluidMoveDurationPropertyKey, new Duration(TimeSpan.FromMilliseconds(200)));
}
else
{
HeaderPanel.SetValue(TabPanel.FluidMoveDurationPropertyKey, new Duration(TimeSpan.FromMilliseconds(0)));
}
HeaderPanel.SetValue(TabPanel.FluidMoveDurationPropertyKey,
IsAnimationEnabled
? new Duration(TimeSpan.FromMilliseconds(200))
: new Duration(TimeSpan.FromMilliseconds(0)));
HeaderPanel.ForceUpdate = true;
HeaderPanel.Measure(new Size(HeaderPanel.DesiredSize.Width, ActualHeight));
HeaderPanel.ForceUpdate = false;
@@ -396,7 +392,7 @@ namespace HandyControl.Controls
{
var argsClosing = new CancelRoutedEventArgs(TabItem.ClosingEvent, item);
if (!(ItemContainerGenerator.ContainerFromItem(item) is TabItem tabItem)) continue;
if (ItemContainerGenerator.ContainerFromItem(item) is not TabItem tabItem) continue;
tabItem.RaiseEvent(argsClosing);
if (argsClosing.Cancel) return;
@@ -208,7 +208,7 @@ namespace HandyControl.Controls
menu.SetBinding(VisibilityProperty, new Binding(ShowContextMenuProperty.Name)
{
Source = this,
Converter = ResourceHelper.GetResource<IValueConverter>(ResourceToken.Boolean2VisibilityConverter)
Converter = ResourceHelper.GetResourceInternal<IValueConverter>(ResourceToken.Boolean2VisibilityConverter)
});
}
}
@@ -20,7 +20,7 @@ namespace HandyControl.Controls
/// <summary>
/// 选项卡字典
/// </summary>
internal Dictionary<int, TabItem> ItemDic = new Dictionary<int, TabItem>();
internal Dictionary<int, TabItem> ItemDic = new();
public static readonly DependencyPropertyKey FluidMoveDurationPropertyKey =
DependencyProperty.RegisterReadOnly("FluidMoveDuration", typeof(Duration), typeof(TabPanel),
@@ -1,10 +1,10 @@
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using HandyControl.Data;
using HandyControl.Tools.Helper;
namespace HandyControl.Controls
{
@@ -201,27 +201,8 @@ namespace HandyControl.Controls
return;
}
#if NET40 || NET45 || NET451 || NET452 || NET46|| NET461
_formattedText = new FormattedText(
Text,
CultureInfo.CurrentUICulture,
FlowDirection,
new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),
FontSize, Fill);
#else
var source = PresentationSource.FromVisual(this);
var dpi = 1.0;
if (source?.CompositionTarget != null)
{
dpi = 96.0 * source.CompositionTarget.TransformToDevice.M11 / 96.0;
}
_formattedText = new FormattedText(
Text,
CultureInfo.CurrentUICulture,
FlowDirection,
new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),
FontSize, Fill, dpi);
#endif
_formattedText = TextHelper.CreateFormattedText(Text, FlowDirection,
new Typeface(FontFamily, FontStyle, FontWeight, FontStretch), FontSize);
UpdateFormattedText();
}
@@ -1,10 +1,10 @@
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using HandyControl.Data;
using HandyControl.Tools.Helper;
namespace HandyControl.Controls
{
@@ -129,27 +129,8 @@ namespace HandyControl.Controls
return;
}
#if NET40 || NET45 || NET451 || NET452 || NET46|| NET461
_formattedText = new FormattedText(
Text,
CultureInfo.CurrentUICulture,
FlowDirection,
new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),
FontSize, Foreground);
#else
var source = PresentationSource.FromVisual(this);
var dpi = 1.0;
if (source?.CompositionTarget != null)
{
dpi = 96.0 * source.CompositionTarget.TransformToDevice.M11 / 96.0;
}
_formattedText = new FormattedText(
Text,
CultureInfo.CurrentUICulture,
FlowDirection,
new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),
FontSize, Foreground, dpi);
#endif
_formattedText = TextHelper.CreateFormattedText(Text, FlowDirection,
new Typeface(FontFamily, FontStyle, FontWeight, FontStretch), FontSize);
UpdateFormattedText();
}
@@ -173,11 +173,7 @@ namespace HandyControl.Controls
{
if (value)
{
if (_isHandlerSuspended == null)
{
_isHandlerSuspended = new Dictionary<DependencyProperty, bool>(2);
}
_isHandlerSuspended ??= new Dictionary<DependencyProperty, bool>(2);
_isHandlerSuspended[property] = true;
}
else
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Controls;
@@ -110,6 +111,7 @@ namespace HandyControl.Controls
selector.ItemsSource = list;
}
[SuppressMessage("ReSharper", "MergeIntoPattern")]
private void Update()
{
if (_hourList.SelectedIndex >= 0 && _hourList.SelectedIndex < 24 &&
@@ -240,10 +240,10 @@ namespace HandyControl.Controls
var positions = new Point3DCollection
{
new Point3D(-quarterWidth * flag, quarterHeight, 0),
new Point3D(-quarterWidth * flag, 0, 0),
new Point3D(quarterWidth * flag, 0, 0),
new Point3D(quarterWidth * flag, quarterHeight, 0)
new(-quarterWidth * flag, quarterHeight, 0),
new(-quarterWidth * flag, 0, 0),
new(quarterWidth * flag, 0, 0),
new(quarterWidth * flag, quarterHeight, 0)
};
var triangleIndices = new Int32Collection
@@ -258,10 +258,10 @@ namespace HandyControl.Controls
var textureCoordinates = new PointCollection
{
new Point(0, 0),
new Point(0, 1),
new Point(1, 1),
new Point(1, 0)
new(0, 0),
new(0, 1),
new(1, 1),
new(1, 0)
};
var geometry3D = new MeshGeometry3D
@@ -114,7 +114,7 @@ namespace HandyControl.Controls
private static void OnSelectedTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is TimeBar timeBar && timeBar._textBlockSelected != null)
if (d is TimeBar { _textBlockSelected: { } } timeBar)
{
timeBar.OnSelectedTimeChanged((DateTime) e.NewValue);
}
@@ -150,7 +150,7 @@ namespace HandyControl.Controls
/// <summary>
/// 刻度集合
/// </summary>
private readonly List<SpeTextBlock> _speBlockList = new List<SpeTextBlock>();
private readonly List<SpeTextBlock> _speBlockList = new();
/// <summary>
/// 初始化时时间
@@ -160,7 +160,7 @@ namespace HandyControl.Controls
/// <summary>
/// 时间段集合
/// </summary>
private readonly List<int> _timeSpeList = new List<int>
private readonly List<int> _timeSpeList = new()
{
7200000,
3600000,
@@ -403,25 +403,17 @@ namespace HandyControl.Controls
/// <returns></returns>
private DateTime TimeConvert(DateTime time)
{
switch (_speIndex)
return _speIndex switch
{
case 0:
return new DateTime(time.Year, time.Month, time.Day, time.Hour / 2 * 2, 0, 0);
case 1:
return new DateTime(time.Year, time.Month, time.Day, time.Hour, 0, 0);
case 2:
return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute / 30 * 30, 0);
case 3:
return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute / 10 * 10, 0);
case 4:
return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute / 5 * 5, 0);
case 5:
return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, 0);
case 6:
return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second / 30 * 30);
default:
return time;
}
0 => new DateTime(time.Year, time.Month, time.Day, time.Hour / 2 * 2, 0, 0),
1 => new DateTime(time.Year, time.Month, time.Day, time.Hour, 0, 0),
2 => new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute / 30 * 30, 0),
3 => new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute / 10 * 10, 0),
4 => new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute / 5 * 5, 0),
5 => new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, 0),
6 => new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second / 30 * 30),
_ => time
};
}
/// <summary>
@@ -22,9 +22,9 @@ namespace HandyControl.Controls
private const string ElementItemsSelected = "PART_ItemsSelected";
private readonly Dictionary<object, TransferEntry> _entryDic = new Dictionary<object, TransferEntry>();
private readonly Dictionary<object, TransferEntry> _entryDic = new();
private readonly List<TransferEntry> _entryList = new List<TransferEntry>();
private readonly List<TransferEntry> _entryList = new();
private SimpleItemsControl _itemsOrigin;
@@ -1,7 +1,7 @@
using System.Runtime.InteropServices;
using System.Windows.Media;
using HandyControl.Data;
using HandyControl.Tools;
using HandyControl.Tools.Helper;
using HandyControl.Tools.Interop;
namespace HandyControl.Controls
@@ -14,36 +14,32 @@ namespace HandyControl.Controls
EnableBlur(this);
}
private static SystemVersionInfo GetSystemVersionInfo()
{
var osv = new InteropValues.RTL_OSVERSIONINFOEX();
osv.dwOSVersionInfoSize = (uint) Marshal.SizeOf(osv);
InteropMethods.Gdip.RtlGetVersion(out osv);
return new SystemVersionInfo((int) osv.dwMajorVersion, (int) osv.dwMinorVersion, (int) osv.dwBuildNumber);
}
internal static void EnableBlur(Window window)
{
var versionInfo = GetSystemVersionInfo();
if (versionInfo < SystemVersionInfo.Windows10 ||
versionInfo >= SystemVersionInfo.Windows10_1903)
{
var colorValue = ResourceHelper.GetResource<uint>(ResourceToken.BlurGradientValue);
var color = ColorHelper.ToColor(colorValue);
color = Color.FromRgb(color.R, color.G, color.B);
window.Background = new SolidColorBrush(color);
return;
}
var versionInfo = SystemHelper.GetSystemVersionInfo();
var accentPolicy = new InteropValues.ACCENTPOLICY();
var accentPolicySize = Marshal.SizeOf(accentPolicy);
accentPolicy.AccentState = versionInfo < SystemVersionInfo.Windows10_1809
? InteropValues.ACCENTSTATE.ACCENT_ENABLE_BLURBEHIND
: InteropValues.ACCENTSTATE.ACCENT_ENABLE_ACRYLICBLURBEHIND;
accentPolicy.AccentFlags = 2;
if (versionInfo >= SystemVersionInfo.Windows10_1903)
{
accentPolicy.AccentState = InteropValues.ACCENTSTATE.ACCENT_ENABLE_BLURBEHIND;
}
else if (versionInfo >= SystemVersionInfo.Windows10_1809)
{
accentPolicy.AccentState = InteropValues.ACCENTSTATE.ACCENT_ENABLE_ACRYLICBLURBEHIND;
}
else if (versionInfo >= SystemVersionInfo.Windows10)
{
accentPolicy.AccentState = InteropValues.ACCENTSTATE.ACCENT_ENABLE_BLURBEHIND;
}
else
{
accentPolicy.AccentState = InteropValues.ACCENTSTATE.ACCENT_ENABLE_TRANSPARENTGRADIENT;
}
accentPolicy.GradientColor = ResourceHelper.GetResource<uint>(ResourceToken.BlurGradientValue);
var accentPtr = Marshal.AllocHGlobal(accentPolicySize);
@@ -248,8 +248,8 @@ namespace HandyControl.Controls
messageBox = CreateMessageBox(null, messageBoxText, caption, MessageBoxButton.OK, MessageBoxImage.None, MessageBoxResult.OK);
SetButtonStatus(messageBox, MessageBoxButton.OK, MessageBoxResult.OK);
messageBox.ShowImage = true;
messageBox.Image = ResourceHelper.GetResource<Geometry>(ResourceToken.SuccessGeometry);
messageBox.ImageBrush = ResourceHelper.GetResource<Brush>(ResourceToken.SuccessBrush);
messageBox.Image = ResourceHelper.GetResourceInternal<Geometry>(ResourceToken.SuccessGeometry);
messageBox.ImageBrush = ResourceHelper.GetResourceInternal<Brush>(ResourceToken.SuccessBrush);
SystemSounds.Asterisk.Play();
messageBox.ShowDialog();
}));
@@ -330,8 +330,8 @@ namespace HandyControl.Controls
messageBox = CreateMessageBox(null, messageBoxText, caption, MessageBoxButton.OK, MessageBoxImage.None, MessageBoxResult.OK);
SetButtonStatus(messageBox, MessageBoxButton.OK, MessageBoxResult.OK);
messageBox.ShowImage = true;
messageBox.Image = ResourceHelper.GetResource<Geometry>(ResourceToken.FatalGeometry);
messageBox.ImageBrush = ResourceHelper.GetResource<Brush>(ResourceToken.PrimaryTextBrush);
messageBox.Image = ResourceHelper.GetResourceInternal<Geometry>(ResourceToken.FatalGeometry);
messageBox.ImageBrush = ResourceHelper.GetResourceInternal<Brush>(ResourceToken.PrimaryTextBrush);
SystemSounds.Asterisk.Play();
messageBox.ShowDialog();
}));
@@ -375,13 +375,13 @@ namespace HandyControl.Controls
if (!string.IsNullOrEmpty(info.IconKey))
{
messageBox.ShowImage = true;
messageBox.Image = ResourceHelper.GetResource<Geometry>(info.IconKey);
messageBox.ImageBrush = ResourceHelper.GetResource<Brush>(info.IconBrushKey);
messageBox.Image = ResourceHelper.GetResourceInternal<Geometry>(info.IconKey);
messageBox.ImageBrush = ResourceHelper.GetResourceInternal<Brush>(info.IconBrushKey);
}
if (info.StyleKey != null)
{
messageBox.Style = ResourceHelper.GetResource<Style>(info.StyleKey);
messageBox.Style = ResourceHelper.GetResourceInternal<Style>(info.StyleKey);
}
SystemSounds.Asterisk.Play();
messageBox.ShowDialog();
@@ -477,7 +477,7 @@ namespace HandyControl.Controls
IsDefault = true,
Content = Lang.Confirm,
Command = ControlCommands.Confirm,
Style = ResourceHelper.GetResource<Style>("MessageBoxButtonStyle")
Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxButtonStyle")
};
break;
@@ -499,15 +499,15 @@ namespace HandyControl.Controls
if (defaultResult == MessageBoxResult.Cancel)
{
messageBox._buttonOk.Style = ResourceHelper.GetResource<Style>("MessageBoxButtonStyle");
messageBox._buttonCancel.Style = ResourceHelper.GetResource<Style>("MessageBoxPrimaryButtonStyle");
messageBox._buttonOk.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxButtonStyle");
messageBox._buttonCancel.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxPrimaryButtonStyle");
messageBox._buttonCancel.IsDefault = true;
}
else
{
messageBox._buttonOk.Style = ResourceHelper.GetResource<Style>("MessageBoxPrimaryButtonStyle");
messageBox._buttonOk.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxPrimaryButtonStyle");
messageBox._buttonOk.IsDefault = true;
messageBox._buttonCancel.Style = ResourceHelper.GetResource<Style>("MessageBoxButtonStyle");
messageBox._buttonCancel.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxButtonStyle");
}
break;
@@ -528,15 +528,15 @@ namespace HandyControl.Controls
if (defaultResult == MessageBoxResult.No)
{
messageBox._buttonYes.Style = ResourceHelper.GetResource<Style>("MessageBoxButtonStyle");
messageBox._buttonNo.Style = ResourceHelper.GetResource<Style>("MessageBoxPrimaryButtonStyle");
messageBox._buttonYes.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxButtonStyle");
messageBox._buttonNo.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxPrimaryButtonStyle");
messageBox._buttonNo.IsDefault = true;
}
else
{
messageBox._buttonYes.Style = ResourceHelper.GetResource<Style>("MessageBoxPrimaryButtonStyle");
messageBox._buttonYes.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxPrimaryButtonStyle");
messageBox._buttonYes.IsDefault = true;
messageBox._buttonNo.Style = ResourceHelper.GetResource<Style>("MessageBoxButtonStyle");
messageBox._buttonNo.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxButtonStyle");
}
break;
@@ -565,24 +565,24 @@ namespace HandyControl.Controls
if (defaultResult == MessageBoxResult.No)
{
messageBox._buttonYes.Style = ResourceHelper.GetResource<Style>("MessageBoxButtonStyle");
messageBox._buttonNo.Style = ResourceHelper.GetResource<Style>("MessageBoxPrimaryButtonStyle");
messageBox._buttonYes.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxButtonStyle");
messageBox._buttonNo.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxPrimaryButtonStyle");
messageBox._buttonNo.IsDefault = true;
messageBox._buttonCancel.Style = ResourceHelper.GetResource<Style>("MessageBoxButtonStyle");
messageBox._buttonCancel.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxButtonStyle");
}
else if (defaultResult == MessageBoxResult.Cancel)
{
messageBox._buttonYes.Style = ResourceHelper.GetResource<Style>("MessageBoxButtonStyle");
messageBox._buttonNo.Style = ResourceHelper.GetResource<Style>("MessageBoxButtonStyle");
messageBox._buttonCancel.Style = ResourceHelper.GetResource<Style>("MessageBoxPrimaryButtonStyle");
messageBox._buttonYes.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxButtonStyle");
messageBox._buttonNo.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxButtonStyle");
messageBox._buttonCancel.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxPrimaryButtonStyle");
messageBox._buttonCancel.IsDefault = true;
}
else
{
messageBox._buttonYes.Style = ResourceHelper.GetResource<Style>("MessageBoxPrimaryButtonStyle");
messageBox._buttonYes.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxPrimaryButtonStyle");
messageBox._buttonYes.IsDefault = true;
messageBox._buttonNo.Style = ResourceHelper.GetResource<Style>("MessageBoxButtonStyle");
messageBox._buttonCancel.Style = ResourceHelper.GetResource<Style>("MessageBoxButtonStyle");
messageBox._buttonNo.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxButtonStyle");
messageBox._buttonCancel.Style = ResourceHelper.GetResourceInternal<Style>("MessageBoxButtonStyle");
}
break;
@@ -616,8 +616,8 @@ namespace HandyControl.Controls
if (string.IsNullOrEmpty(iconKey)) return;
messageBox.ShowImage = true;
messageBox.Image = ResourceHelper.GetResource<Geometry>(iconKey);
messageBox.ImageBrush = ResourceHelper.GetResource<Brush>(iconBrushKey);
messageBox.Image = ResourceHelper.GetResourceInternal<Geometry>(iconKey);
messageBox.ImageBrush = ResourceHelper.GetResourceInternal<Brush>(iconBrushKey);
}
private static bool IsValidMessageBoxButton(MessageBoxButton value)
@@ -628,6 +628,7 @@ namespace HandyControl.Controls
|| value == MessageBoxButton.YesNoCancel;
}
[SuppressMessage("ReSharper", "ConditionIsAlwaysTrueOrFalse")]
private static bool IsValidMessageBoxImage(MessageBoxImage value)
{
return value == MessageBoxImage.Asterisk
@@ -187,7 +187,7 @@ namespace HandyControl.Controls
WindowStyle = WindowStyle.None,
ContentStr = message,
WindowStartupLocation = WindowStartupLocation.CenterScreen,
Background = ResourceHelper.GetResource<Brush>(ResourceToken.PrimaryBrush)
Background = ResourceHelper.GetResourceInternal<Brush>(ResourceToken.PrimaryBrush)
};
window.Show();
}
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more