Adjust project structure

This commit is contained in:
NaBian committed 2019-04-10 00:53:59 +08:00
1 parent 89875792aa
commit 16ef430a39
82 files changed
+271 -10113

No files matched your search

@@ -93,21 +93,6 @@
<Compile Include="UserControl\Main\NoUserContent.xaml.cs">
<DependentUpon>NoUserContent.xaml</DependentUpon>
</Compile>
<Compile Include="ViewModel\Basic\ChatBoxViewModel.cs" />
<Compile Include="ViewModel\Basic\InteractiveDialogViewModel.cs" />
<Compile Include="ViewModel\Controls\BadgeDemoViewModel.cs" />
<Compile Include="ViewModel\Controls\DialogDemoViewModel.cs" />
<Compile Include="ViewModel\Controls\GrowlDemoViewModel.cs" />
<Compile Include="ViewModel\Controls\ImageBrowserDemoViewModel.cs" />
<Compile Include="ViewModel\Controls\NotifyIconDemoViewModel.cs" />
<Compile Include="ViewModel\Controls\PaginationDemoViewModel.cs" />
<Compile Include="ViewModel\Controls\SearchBarDemoViewModel.cs" />
<Compile Include="ViewModel\Controls\StepBarDemoViewModel.cs" />
<Compile Include="ViewModel\Controls\WindowDemoViewModel.cs" />
<Compile Include="ViewModel\DemoViewModelBase!1.cs" />
<Compile Include="ViewModel\Main\ContributorsViewModel.cs" />
<Compile Include="ViewModel\Main\MainViewModel.cs" />
<Compile Include="ViewModel\ViewModelLocator.cs" />
</ItemGroup>
<ItemGroup>
<Resource Include="..\..\Shared\HandyControlDemo_Shared\Resources\Img\1.jpg">
@@ -1,172 +0,0 @@
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Media;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using HandyControl.Controls;
using HandyControl.Data;
using HandyControl.Tools;
using HandyControlDemo.Data;
using HandyControlDemo.Tools;
using Microsoft.Win32;
namespace HandyControlDemo.ViewModel
{
public class ChatBoxViewModel : ViewModelBase
{
private static readonly string AudioCachePath = $"{AppDomain.CurrentDomain.BaseDirectory}Cache";
private readonly string _id = Guid.NewGuid().ToString();
private readonly Stopwatch _stopwatch = new Lazy<Stopwatch>(() => new Stopwatch()).Value;
public ChatBoxViewModel()
{
Messenger.Default.Register<ChatInfoModel>(this, MessageToken.SendChatMessage, ReceiveMessage);
}
private void ReceiveMessage(ChatInfoModel info)
{
if (_id.Equals(info.SenderId)) return;
info.Role = ChatRoleType.Receiver;
ChatInfos.Add(info);
}
private string _chatString;
public string ChatString
{
get => _chatString;
set => Set(ref _chatString, value);
}
public ObservableCollection<ChatInfoModel> ChatInfos { get; set; } = new ObservableCollection<ChatInfoModel>();
public RelayCommand<KeyEventArgs> SendStringCmd => new Lazy<RelayCommand<KeyEventArgs>>(() =>
new RelayCommand<KeyEventArgs>(SendString)).Value;
private void SendString(KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
if (string.IsNullOrEmpty(ChatString)) return;
var info = new ChatInfoModel
{
Message = ChatString,
SenderId = _id,
Type = ChatMessageType.String,
Role = ChatRoleType.Sender
};
ChatInfos.Add(info);
Messenger.Default.Send(info, MessageToken.SendChatMessage);
ChatString = string.Empty;
}
}
public RelayCommand<RoutedEventArgs> ReadMessageCmd => new Lazy<RelayCommand<RoutedEventArgs>>(() =>
new RelayCommand<RoutedEventArgs>(ReadMessage)).Value;
private void ReadMessage(RoutedEventArgs e)
{
if (e.OriginalSource is FrameworkElement element && element.Tag is ChatInfoModel info)
{
if (info.Type == ChatMessageType.Image)
{
new ImageBrowser(new Uri(info.Enclosure.ToString()))
{
Owner = VisualHelper.GetActiveWindow()
}.Show();
}
else if (info.Type == ChatMessageType.Audio)
{
var player = new SoundPlayer(info.Enclosure.ToString());
player.PlaySync();
}
}
}
public RelayCommand StartRecordCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(StartRecord)).Value;
private void StartRecord()
{
ExternDllHelper.MciSendString("set wave bitpersample 8", "", 0, 0);
ExternDllHelper.MciSendString("set wave samplespersec 20000", "", 0, 0);
ExternDllHelper.MciSendString("set wave channels 2", "", 0, 0);
ExternDllHelper.MciSendString("set wave format tag pcm", "", 0, 0);
ExternDllHelper.MciSendString("open new type WAVEAudio alias movie", "", 0, 0);
ExternDllHelper.MciSendString("record movie", "", 0, 0);
_stopwatch.Reset();
_stopwatch.Start();
}
public RelayCommand StopRecordCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(StopRecord)).Value;
private void StopRecord()
{
if (!Directory.Exists(AudioCachePath))
{
try
{
Directory.CreateDirectory(AudioCachePath);
}
catch (Exception e)
{
Growl.Error(e.Message);
return;
}
}
var cachePath = $"{AudioCachePath}\\{Guid.NewGuid().ToString()}";
ExternDllHelper.MciSendString("stop movie", "", 0, 0);
ExternDllHelper.MciSendString($"save movie {cachePath}", "", 0, 0);
ExternDllHelper.MciSendString("close movie", "", 0, 0);
_stopwatch.Stop();
var info = new ChatInfoModel
{
Message = $"{_stopwatch.Elapsed.Seconds.ToString()} {Properties.Langs.Lang.Second}",
SenderId = _id,
Type = ChatMessageType.Audio,
Role = ChatRoleType.Sender,
Enclosure = cachePath
};
ChatInfos.Add(info);
Messenger.Default.Send(info, MessageToken.SendChatMessage);
}
public RelayCommand OpenImageCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(OpenImage)).Value;
private void OpenImage()
{
var dialog = new OpenFileDialog();
if (dialog.ShowDialog() == true)
{
var fileName = dialog.FileName;
if (File.Exists(fileName))
{
var info = new ChatInfoModel
{
Message = BitmapFrame.Create(new Uri(fileName)),
SenderId = _id,
Type = ChatMessageType.Image,
Role = ChatRoleType.Sender,
Enclosure = fileName
};
ChatInfos.Add(info);
Messenger.Default.Send(info, MessageToken.SendChatMessage);
}
}
}
}
}
@@ -1,30 +0,0 @@
using System;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using HandyControl.Tools.Extension;
namespace HandyControlDemo.ViewModel.Basic
{
public class InteractiveDialogViewModel : ViewModelBase, IDialogResultable<string>
{
public Action CloseAction { get; set; }
private string _result;
public string Result
{
get => _result;
set => Set(ref _result, value);
}
private string _message;
public string Message
{
get => _message;
set => Set(ref _message, value);
}
public RelayCommand CloseCmd => new Lazy<RelayCommand>(() => new RelayCommand(() => CloseAction?.Invoke())).Value;
}
}
@@ -1,20 +0,0 @@
using System;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
namespace HandyControlDemo.ViewModel.Controls
{
public class BadgeDemoViewModel : ViewModelBase
{
private int _count = 1;
public int Count
{
get => _count;
set => Set(ref _count, value);
}
public RelayCommand CountCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Count++)).Value;
}
}
@@ -1,41 +0,0 @@
using System;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using HandyControl.Controls;
using HandyControl.Tools.Extension;
using HandyControlDemo.UserControl;
using HandyControlDemo.UserControl.Basic;
using HandyControlDemo.ViewModel.Basic;
namespace HandyControlDemo.ViewModel
{
public class DialogDemoViewModel : ViewModelBase
{
private string _dialogResult;
public string DialogResult
{
get => _dialogResult;
set => Set(ref _dialogResult, value);
}
public RelayCommand ShowTextCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(ShowText)).Value;
private void ShowText()
{
Dialog.Show(new TextDialog());
}
public RelayCommand ShowInteractiveDialogCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(async () => await ShowInteractiveDialog())).Value;
private async Task ShowInteractiveDialog()
{
DialogResult = await Dialog.Show<InteractiveDialog>()
.Initialize<InteractiveDialogViewModel>(vm => vm.Message = DialogResult)
.GetResultAsync<string>();
}
}
}
@@ -1,66 +0,0 @@
using System;
using GalaSoft.MvvmLight.CommandWpf;
using HandyControl.Controls;
using HandyControl.Data;
using HandyControlDemo.Window;
namespace HandyControlDemo.ViewModel
{
public class GrowlDemoViewModel
{
private readonly string _token;
public GrowlDemoViewModel()
{
}
public GrowlDemoViewModel(string token)
{
_token = token;
}
public RelayCommand InfoCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.Info(Properties.Langs.Lang.GrowlInfo, _token))).Value;
public RelayCommand SuccessCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.Success(Properties.Langs.Lang.GrowlSuccess, _token))).Value;
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 =>
{
Growl.Info(isConfirmed.ToString());
return true;
}, _token))).Value;
public RelayCommand FatalCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.Fatal(new GrowlInfo
{
Message = Properties.Langs.Lang.GrowlFatal,
ShowDateTime = false,
Token = _token
}))).Value;
public RelayCommand ClearCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => Growl.Clear(_token))).Value;
public RelayCommand NewWindowCmd => new Lazy<RelayCommand>(() =>
new RelayCommand(() => new GrowlDemoWindow().Show())).Value;
}
}
@@ -1,13 +0,0 @@
using System;
using GalaSoft.MvvmLight.CommandWpf;
using HandyControl.Controls;
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;
}
}
@@ -1,54 +0,0 @@
using System;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using HandyControl.Controls;
using HandyControlDemo.Data;
namespace HandyControlDemo.ViewModel
{
public class NotifyIconDemoViewModel : ViewModelBase
{
private bool _contextMenuIsShow;
public bool ContextMenuIsShow
{
get => _contextMenuIsShow;
set
{
Set(ref _contextMenuIsShow, value);
GlobalData.NotifyIconIsShow = ContextMenuIsShow || ContextContentIsShow;
}
}
private bool _contextMenuIsBlink;
public bool ContextMenuIsBlink
{
get => _contextMenuIsBlink;
set => Set(ref _contextMenuIsBlink, value);
}
private bool _contextContentIsShow;
public bool ContextContentIsShow
{
get => _contextContentIsShow;
set
{
Set(ref _contextContentIsShow, value);
GlobalData.NotifyIconIsShow = ContextMenuIsShow || ContextContentIsShow;
}
}
private bool _contextContentIsBlink;
public bool ContextContentIsBlink
{
get => _contextContentIsBlink;
set => Set(ref _contextContentIsBlink, value);
}
public RelayCommand<object> MouseCmd => new Lazy<RelayCommand<object>>(() =>
new RelayCommand<object>(str=> Growl.Info(str.ToString()))).Value;
}
}
@@ -1,53 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using GalaSoft.MvvmLight.CommandWpf;
using HandyControl.Data;
using HandyControlDemo.Data;
using HandyControlDemo.Service;
namespace HandyControlDemo.ViewModel
{
public class PaginationDemoViewModel : DemoViewModelBase<DemoDataModel>
{
/// <summary>
/// 所有数据
/// </summary>
private readonly List<DemoDataModel> _totalDataList;
/// <summary>
/// 页码
/// </summary>
private int _pageIndex = 1;
/// <summary>
/// 页码
/// </summary>
public int PageIndex
{
get => _pageIndex;
set => Set(ref _pageIndex, value);
}
public PaginationDemoViewModel(DataService dataService)
{
_totalDataList = dataService.GetDemoDataList(100);
DataList = _totalDataList.Take(10).ToList();
}
/// <summary>
/// 页码改变命令
/// </summary>
public RelayCommand<FunctionEventArgs<int>> PageUpdatedCmd =>
new Lazy<RelayCommand<FunctionEventArgs<int>>>(() =>
new RelayCommand<FunctionEventArgs<int>>(PageUpdated)).Value;
/// <summary>
/// 页码改变
/// </summary>
private void PageUpdated(FunctionEventArgs<int> info)
{
DataList = _totalDataList.Skip((info.Info - 1) * 10).Take(10).ToList();
}
}
}
@@ -1,18 +0,0 @@
using System;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using HandyControl.Controls;
namespace HandyControlDemo.ViewModel
{
public class SearchBarDemoViewModel : ViewModelBase
{
public RelayCommand<string> SearchCmd => new Lazy<RelayCommand<string>>(() =>
new RelayCommand<string>(Search)).Value;
private void Search(string key)
{
Growl.Info(key);
}
}
}
@@ -1,41 +0,0 @@
using System;
using System.Linq;
using System.Windows.Controls;
using GalaSoft.MvvmLight.CommandWpf;
using HandyControl.Controls;
using HandyControlDemo.Data;
using HandyControlDemo.Service;
namespace HandyControlDemo.ViewModel
{
public class StepBarDemoViewModel : DemoViewModelBase<StepBarDemoModel>
{
public StepBarDemoViewModel(DataService dataService) => DataList = dataService.GetStepBarDemoDataList();
/// <summary>
/// 下一步
/// </summary>
public RelayCommand<Panel> NextCmd => new Lazy<RelayCommand<Panel>>(() => new RelayCommand<Panel>(Next)).Value;
/// <summary>
/// 上一步
/// </summary>
public RelayCommand<Panel> PrevCmd => new Lazy<RelayCommand<Panel>>(() => new RelayCommand<Panel>(Prev)).Value;
private void Next(Panel panel)
{
foreach (var stepBar in panel.Children.OfType<StepBar>())
{
stepBar.Next();
}
}
private void Prev(Panel panel)
{
foreach (var stepBar in panel.Children.OfType<StepBar>())
{
stepBar.Prev();
}
}
}
}
@@ -1,21 +0,0 @@
using System;
using System.Windows;
using GalaSoft.MvvmLight.CommandWpf;
using HandyControlDemo.Tools;
namespace HandyControlDemo.ViewModel
{
public class WindowDemoViewModel
{
public RelayCommand<string> OpenWindowCmd => new Lazy<RelayCommand<string>>(() => new RelayCommand<string>(OpenWindow)).Value;
private void OpenWindow(string windowTag)
{
if (AssemblyHelper.CreateInternalInstance($"Window.{windowTag}") is System.Windows.Window window)
{
window.Owner = Application.Current.MainWindow;
window.ShowDialog();
}
}
}
}
@@ -1,22 +0,0 @@
using System.Collections.Generic;
using GalaSoft.MvvmLight;
namespace HandyControlDemo.ViewModel
{
public class DemoViewModelBase<T> : ViewModelBase
{
/// <summary>
/// 数据列表
/// </summary>
private IList<T> _dataList;
/// <summary>
/// 数据列表
/// </summary>
public IList<T> DataList
{
get => _dataList;
set => Set(ref _dataList, value);
}
}
}
@@ -1,17 +0,0 @@
using System.Threading.Tasks;
using HandyControlDemo.Data;
using HandyControlDemo.Service;
namespace HandyControlDemo.ViewModel
{
public class ContributorsViewModel : DemoViewModelBase<ContributorModel>
{
public ContributorsViewModel(DataService dataService)
{
Task.Run(() =>
{
DataList = dataService.GetContributorDataList();
});
}
}
}
@@ -1,113 +0,0 @@
using System;
using System.Windows.Controls;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using HandyControlDemo.Data;
using HandyControlDemo.Service;
using HandyControlDemo.Tools;
namespace HandyControlDemo.ViewModel
{
public class MainViewModel : DemoViewModelBase<DemoDataModel>
{
#region 字段
/// <summary>
/// 内容标题
/// </summary>
private object _contentTitle;
/// <summary>
/// 子内容
/// </summary>
private object _subContent;
/// <summary>
/// 当前选中的列表项
/// </summary>
private ListBoxItem _listBoxItemCurrent;
#endregion
public MainViewModel(DataService dataService)
{
Messenger.Default.Register<object>(this, MessageToken.LoadShowContent, obj =>
{
if (SubContent is IDisposable disposable)
{
disposable.Dispose();
}
SubContent = obj;
});
Messenger.Default.Register<object>(this, MessageToken.ClearLeftSelected, obj =>
{
if (_listBoxItemCurrent == null) return;
_listBoxItemCurrent.IsSelected = false;
_listBoxItemCurrent = null;
});
DataList = dataService.GetDemoDataList();
}
#region 属性
/// <summary>
/// 子内容
/// </summary>
public object SubContent
{
get => _subContent;
set => Set(ref _subContent, value);
}
/// <summary>
/// 内容标题
/// </summary>
public object ContentTitle
{
get => _contentTitle;
set => Set(ref _contentTitle, value);
}
#endregion
#region 命令
/// <summary>
/// 切换例子命令
/// </summary>
public RelayCommand<SelectionChangedEventArgs> SwitchDemoCmd =>
new Lazy<RelayCommand<SelectionChangedEventArgs>>(() =>
new RelayCommand<SelectionChangedEventArgs>(SwitchDemo)).Value;
#endregion
#region 方法
/// <summary>
/// 切换例子
/// </summary>
private void SwitchDemo(SelectionChangedEventArgs e)
{
if (e.AddedItems.Count == 0) return;
if (e.AddedItems[0] is ListBoxItem item)
{
if (item.Tag is string tag)
{
if (Equals(_listBoxItemCurrent, item)) return;
_listBoxItemCurrent = item;
ContentTitle = item.Content;
Messenger.Default.Send(false, MessageToken.FullSwitch);
Messenger.Default.Send(AssemblyHelper.CreateInternalInstance($"UserControl.{tag}"), MessageToken.LoadShowContent);
}
else
{
_listBoxItemCurrent = null;
ContentTitle = null;
SubContent = null;
}
}
}
#endregion
}
}
@@ -1,76 +0,0 @@
using System;
using System.Windows;
using CommonServiceLocator;
using GalaSoft.MvvmLight.Ioc;
using HandyControlDemo.Data;
using HandyControlDemo.Service;
using HandyControlDemo.ViewModel.Basic;
using HandyControlDemo.ViewModel.Controls;
namespace HandyControlDemo.ViewModel
{
public class ViewModelLocator
{
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<DataService>();
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register(() => new GrowlDemoViewModel(), "GrowlDemo");
SimpleIoc.Default.Register(() => new GrowlDemoViewModel(MessageToken.GrowlDemoPanel), "GrowlDemoWithToken");
SimpleIoc.Default.Register<ImageBrowserDemoViewModel>();
SimpleIoc.Default.Register<ComboBoxDemoViewModel>();
SimpleIoc.Default.Register<WindowDemoViewModel>();
SimpleIoc.Default.Register<ContributorsViewModel>();
SimpleIoc.Default.Register<StepBarDemoViewModel>();
SimpleIoc.Default.Register<PaginationDemoViewModel>();
SimpleIoc.Default.Register<ChatBoxViewModel>();
SimpleIoc.Default.Register<CoverViewModel>();
SimpleIoc.Default.Register<DialogDemoViewModel>();
SimpleIoc.Default.Register<SearchBarDemoViewModel>();
SimpleIoc.Default.Register<NotifyIconDemoViewModel>();
SimpleIoc.Default.Register<InteractiveDialogViewModel>();
SimpleIoc.Default.Register<BadgeDemoViewModel>();
}
public static ViewModelLocator Instance => new Lazy<ViewModelLocator>(() =>
Application.Current.TryFindResource("Locator") as ViewModelLocator).Value;
#region Vm
public MainViewModel Main => ServiceLocator.Current.GetInstance<MainViewModel>();
public GrowlDemoViewModel GrowlDemo => ServiceLocator.Current.GetInstance<GrowlDemoViewModel>("GrowlDemo");
public GrowlDemoViewModel GrowlDemoWithToken => ServiceLocator.Current.GetInstance<GrowlDemoViewModel>("GrowlDemoWithToken");
public ImageBrowserDemoViewModel ImageBrowserDemo => ServiceLocator.Current.GetInstance<ImageBrowserDemoViewModel>();
public ComboBoxDemoViewModel ComboBoxDemo => ServiceLocator.Current.GetInstance<ComboBoxDemoViewModel>();
public WindowDemoViewModel WindowDemo => ServiceLocator.Current.GetInstance<WindowDemoViewModel>();
public ContributorsViewModel ContributorsView => ServiceLocator.Current.GetInstance<ContributorsViewModel>();
public StepBarDemoViewModel StepBarDemo => ServiceLocator.Current.GetInstance<StepBarDemoViewModel>();
public PaginationDemoViewModel PaginationDemo => ServiceLocator.Current.GetInstance<PaginationDemoViewModel>();
public ChatBoxViewModel ChatBox => new ChatBoxViewModel();
public CoverViewModel CoverView => ServiceLocator.Current.GetInstance<CoverViewModel>();
public DialogDemoViewModel DialogDemo => ServiceLocator.Current.GetInstance<DialogDemoViewModel>();
public SearchBarDemoViewModel SearchBarDemo => ServiceLocator.Current.GetInstance<SearchBarDemoViewModel>();
public NotifyIconDemoViewModel NotifyIconDemo => ServiceLocator.Current.GetInstance<NotifyIconDemoViewModel>();
public InteractiveDialogViewModel InteractiveDialog => ServiceLocator.Current.GetInstance<InteractiveDialogViewModel>();
public BadgeDemoViewModel BadgeDemo => ServiceLocator.Current.GetInstance<BadgeDemoViewModel>();
#endregion
}
}
@@ -1,601 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using HandyControl.Data;
using HandyControl.Interactivity;
using HandyControl.Tools;
using HandyControl.Tools.Extension;
namespace HandyControl.Controls
{
/// <summary>
/// 消息提醒
/// </summary>
[TemplatePart(Name = ElementPanelMore, Type = typeof(Panel))]
[TemplatePart(Name = ElementGridMain, Type = typeof(Grid))]
[TemplatePart(Name = ElementButtonClose, Type = typeof(Button))]
public class Growl : Control
{
#region Constants
private const string ElementPanelMore = "PART_PanelMore";
private const string ElementGridMain = "PART_GridMain";
private const string ElementButtonClose = "PART_ButtonClose";
#endregion Constants
#region Data
private Panel _panelMore;
private Grid _gridMain;
private Button _buttonClose;
private bool _showCloseButton;
private bool _staysOpen;
private int _waitTime = 6;
/// <summary>
/// 计数
/// </summary>
private int _tickCount;
/// <summary>
/// 关闭计时器
/// </summary>
private DispatcherTimer _timerClose;
private static readonly Dictionary<string, Panel> PanelDic = new Dictionary<string, Panel>();
#endregion Data
public Growl()
{
CommandBindings.Add(new CommandBinding(ControlCommands.Close, ButtonClose_OnClick));
CommandBindings.Add(new CommandBinding(ControlCommands.Cancel, ButtonCancel_OnClick));
CommandBindings.Add(new CommandBinding(ControlCommands.Confirm, ButtonOk_OnClick));
}
public static void Register(string token, Panel panel)
{
if (string.IsNullOrEmpty(token) || panel == null) return;
PanelDic[token] = panel;
InitGrowlPanel(panel);
}
public static void Unregister(string token, Panel panel)
{
if (string.IsNullOrEmpty(token) || panel == null) return;
if (PanelDic.ContainsKey(token))
{
if (ReferenceEquals(PanelDic[token], panel))
{
PanelDic.Remove(token);
panel.ContextMenu = null;
panel.SetCurrentValue(PanelElement.FluidMoveBehaviorProperty, DependencyProperty.UnsetValue);
}
}
}
public static void Unregister(Panel panel)
{
if (panel == null) return;
var first = PanelDic.FirstOrDefault(item => ReferenceEquals(panel, item.Value));
if (!string.IsNullOrEmpty(first.Key))
{
PanelDic.Remove(first.Key);
panel.ContextMenu = null;
panel.SetCurrentValue(PanelElement.FluidMoveBehaviorProperty, DependencyProperty.UnsetValue);
}
}
protected override void OnMouseEnter(MouseEventArgs e)
{
base.OnMouseEnter(e);
_buttonClose.Show(_showCloseButton);
}
protected override void OnMouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
_buttonClose.Collapse();
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_panelMore = GetTemplateChild(ElementPanelMore) as Panel;
_gridMain = GetTemplateChild(ElementGridMain) as Grid;
_buttonClose = GetTemplateChild(ElementButtonClose) as Button;
CheckNull();
Update();
}
private void CheckNull()
{
if (_panelMore == null || _gridMain == null || _buttonClose == null) throw new Exception();
}
private Func<bool, bool> ActionBeforeClose { get; set; }
/// <summary>
/// 消息容器
/// </summary>
public static Panel GrowlPanel { get; set; }
internal static readonly DependencyProperty CancelStrProperty = DependencyProperty.Register(
"CancelStr", typeof(string), typeof(Growl), new PropertyMetadata(default(string)));
internal static readonly DependencyProperty ConfirmStrProperty = DependencyProperty.Register(
"ConfirmStr", typeof(string), typeof(Growl), new PropertyMetadata(default(string)));
public static readonly DependencyProperty ShowDateTimeProperty = DependencyProperty.Register(
"ShowDateTime", typeof(bool), typeof(Growl), new PropertyMetadata(ValueBoxes.TrueBox));
public static readonly DependencyProperty MessageProperty = DependencyProperty.Register(
"Message", typeof(string), typeof(Growl), new PropertyMetadata(default(string)));
public static readonly DependencyProperty TimeProperty = DependencyProperty.Register(
"Time", typeof(DateTime), typeof(Growl), new PropertyMetadata(default(DateTime)));
public static readonly DependencyProperty IconProperty = DependencyProperty.Register(
"Icon", typeof(Geometry), typeof(Growl), new PropertyMetadata(default(Geometry)));
public static readonly DependencyProperty IconBrushProperty = DependencyProperty.Register(
"IconBrush", typeof(Brush), typeof(Growl), new PropertyMetadata(default(Brush)));
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));
private static void OnTokenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is Panel panel)
{
if (e.NewValue == null)
{
Unregister(panel);
}
else
{
Register(e.NewValue.ToString(), panel);
}
}
}
public static void SetToken(DependencyObject element, string value)
=> element.SetValue(TokenProperty, value);
public static string GetToken(DependencyObject element)
=> (string) element.GetValue(TokenProperty);
public static void SetGrowlParent(DependencyObject element, bool value) => element.SetValue(GrowlParentProperty, value);
public static bool GetGrowlParent(DependencyObject element) => (bool)element.GetValue(GrowlParentProperty);
public InfoType Type
{
get => (InfoType)GetValue(TypeProperty);
set => SetValue(TypeProperty, value);
}
internal string CancelStr
{
get => (string)GetValue(CancelStrProperty);
set => SetValue(CancelStrProperty, value);
}
internal string ConfirmStr
{
get => (string)GetValue(ConfirmStrProperty);
set => SetValue(ConfirmStrProperty, value);
}
public bool ShowDateTime
{
get => (bool)GetValue(ShowDateTimeProperty);
set => SetValue(ShowDateTimeProperty, value);
}
public string Message
{
get => (string)GetValue(MessageProperty);
set => SetValue(MessageProperty, value);
}
public DateTime Time
{
get => (DateTime)GetValue(TimeProperty);
set => SetValue(TimeProperty, value);
}
public Geometry Icon
{
get => (Geometry)GetValue(IconProperty);
set => SetValue(IconProperty, value);
}
public Brush IconBrush
{
get => (Brush)GetValue(IconBrushProperty);
set => SetValue(IconBrushProperty, value);
}
/// <summary>
/// 开始计时器
/// </summary>
private void StartTimer()
{
_timerClose = new DispatcherTimer
{
Interval = TimeSpan.FromSeconds(1)
};
_timerClose.Tick += delegate
{
if (IsMouseOver)
{
_tickCount = 0;
return;
}
_tickCount++;
if (_tickCount >= _waitTime) Close();
};
_timerClose.Start();
}
/// <summary>
/// 消息容器
/// </summary>
/// <param name="panel"></param>
private static void SetGrowlPanel(Panel panel)
{
GrowlPanel = panel;
InitGrowlPanel(panel);
}
private static void InitGrowlPanel(Panel panel)
{
var menuItem = new MenuItem
{
Header = Properties.Langs.Lang.Clear
};
menuItem.Click += (s, e) =>
{
foreach (var item in panel.Children.OfType<Growl>())
{
item.Close();
}
};
panel.ContextMenu = new ContextMenu
{
Items =
{
menuItem
}
};
PanelElement.SetFluidMoveBehavior(panel, ResourceHelper.GetResource<FluidMoveBehavior>(ResourceToken.BehaviorXY400));
}
private void Update()
{
if (ActionBeforeClose != null)
{
_staysOpen = true;
_showCloseButton = false;
_panelMore.IsEnabled = true;
_panelMore.Show();
}
var transform = new TranslateTransform
{
X = MaxWidth
};
_gridMain.RenderTransform = transform;
transform.BeginAnimation(TranslateTransform.XProperty, AnimationHelper.CreateAnimation(0));
if (!_staysOpen) StartTimer();
}
/// <summary>
/// 显示信息
/// </summary>
/// <param name="growlInfo"></param>
private static void Show(GrowlInfo growlInfo)
{
Application.Current.Dispatcher.Invoke(() =>
{
var ctl = new Growl
{
Message = growlInfo.Message,
Time = DateTime.Now,
Icon = ResourceHelper.GetResource<Geometry>(growlInfo.IconKey),
IconBrush = ResourceHelper.GetResource<Brush>(growlInfo.IconBrushKey),
_showCloseButton = growlInfo.ShowCloseButton,
ActionBeforeClose = growlInfo.ActionBeforeClose,
_staysOpen = growlInfo.StaysOpen,
ShowDateTime = growlInfo.ShowDateTime,
ConfirmStr = growlInfo.ConfirmStr,
CancelStr = growlInfo.CancelStr,
Type = growlInfo.Type,
_waitTime = Math.Max(growlInfo.WaitTime, 2)
};
if (!string.IsNullOrEmpty(growlInfo.Token))
{
if (PanelDic.TryGetValue(growlInfo.Token, out var panel))
{
panel?.Children.Insert(0, ctl);
}
}
else
{
GrowlPanel.Children.Insert(0, ctl);
}
});
}
/// <summary>
/// 成功
/// </summary>
/// <param name="message"></param>
/// <param name="token"></param>
public static void Success(string message, string token = "") => Success(new GrowlInfo
{
Message = message,
Token = token
});
/// <summary>
/// 成功
/// </summary>
/// <param name="growlInfo"></param>
public static void Success(GrowlInfo growlInfo)
{
if (growlInfo == null) throw new ArgumentNullException(nameof(growlInfo));
if (!growlInfo.IsCustom)
{
growlInfo.IconKey = ResourceToken.SuccessGeometry;
growlInfo.IconBrushKey = ResourceToken.SuccessBrush;
growlInfo.Type = InfoType.Success;
}
Show(growlInfo);
}
/// <summary>
/// 消息
/// </summary>
/// <param name="message"></param>
/// <param name="token"></param>
public static void Info(string message, string token = "") => Info(new GrowlInfo
{
Message = message,
Token = token
});
/// <summary>
/// 消息
/// </summary>
/// <param name="growlInfo"></param>
public static void Info(GrowlInfo growlInfo)
{
if (growlInfo == null) throw new ArgumentNullException(nameof(growlInfo));
if (!growlInfo.IsCustom)
{
growlInfo.IconKey = ResourceToken.InfoGeometry;
growlInfo.IconBrushKey = ResourceToken.InfoBrush;
growlInfo.Type = InfoType.Info;
}
Show(growlInfo);
}
/// <summary>
/// 警告
/// </summary>
/// <param name="message"></param>
/// <param name="token"></param>
public static void Warning(string message, string token = "") => Warning(new GrowlInfo
{
Message = message,
Token = token
});
/// <summary>
/// 警告
/// </summary>
/// <param name="growlInfo"></param>
public static void Warning(GrowlInfo growlInfo)
{
if (growlInfo == null) throw new ArgumentNullException(nameof(growlInfo));
if (!growlInfo.IsCustom)
{
growlInfo.IconKey = ResourceToken.WarningGeometry;
growlInfo.IconBrushKey = ResourceToken.WarningBrush;
growlInfo.Type = InfoType.Warning;
}
Show(growlInfo);
}
/// <summary>
/// 错误
/// </summary>
/// <param name="message"></param>
/// <param name="token"></param>
public static void Error(string message, string token = "") => Error(new GrowlInfo
{
Message = message,
Token = token
});
/// <summary>
/// 错误
/// </summary>
/// <param name="growlInfo"></param>
public static void Error(GrowlInfo growlInfo)
{
if (growlInfo == null) throw new ArgumentNullException(nameof(growlInfo));
if (!growlInfo.IsCustom)
{
growlInfo.IconKey = ResourceToken.ErrorGeometry;
growlInfo.IconBrushKey = ResourceToken.DangerBrush;
growlInfo.StaysOpen = true;
growlInfo.Type = InfoType.Error;
}
Show(growlInfo);
}
/// <summary>
/// 严重
/// </summary>
/// <param name="message"></param>
/// <param name="token"></param>
public static void Fatal(string message, string token = "") => Fatal(new GrowlInfo
{
Message = message,
Token = token
});
/// <summary>
/// 严重
/// </summary>
/// <param name="growlInfo"></param>
public static void Fatal(GrowlInfo growlInfo)
{
if (growlInfo == null) throw new ArgumentNullException(nameof(growlInfo));
if (!growlInfo.IsCustom)
{
growlInfo.IconKey = ResourceToken.FatalGeometry;
growlInfo.IconBrushKey = ResourceToken.PrimaryTextBrush;
growlInfo.StaysOpen = true;
growlInfo.ShowCloseButton = false;
growlInfo.Type = InfoType.Fatal;
if (GrowlPanel.ContextMenu != null) GrowlPanel.ContextMenu.Opacity = 0;
}
Show(growlInfo);
}
/// <summary>
/// 询问
/// </summary>
/// <param name="message"></param>
/// <param name="actionBeforeClose"></param>
/// <param name="token"></param>
public static void Ask(string message, Func<bool, bool> actionBeforeClose, string token = "") => Ask(new GrowlInfo
{
Message = message,
ActionBeforeClose = actionBeforeClose,
Token = token
});
/// <summary>
/// 询问
/// </summary>
/// <param name="growlInfo"></param>
public static void Ask(GrowlInfo growlInfo)
{
if (growlInfo == null) throw new ArgumentNullException(nameof(growlInfo));
if (!growlInfo.IsCustom)
{
growlInfo.IconKey = ResourceToken.AskGeometry;
growlInfo.IconBrushKey = ResourceToken.AccentBrush;
growlInfo.StaysOpen = true;
growlInfo.ShowCloseButton = false;
growlInfo.Type = InfoType.Ask;
}
Show(growlInfo);
}
private void ButtonClose_OnClick(object sender, RoutedEventArgs e) => Close();
/// <summary>
/// 关闭
/// </summary>
private void Close()
{
_timerClose?.Stop();
var transform = new TranslateTransform();
_gridMain.RenderTransform = transform;
var animation = AnimationHelper.CreateAnimation(MaxWidth);
animation.Completed += (s, e) =>
{
if (Parent is Panel panel)
{
panel.Children.Remove(this);
}
};
transform.BeginAnimation(TranslateTransform.XProperty, animation);
}
/// <summary>
/// 清除
/// </summary>
/// <param name="token"></param>
public static void Clear(string token = "")
{
if (!string.IsNullOrEmpty(token))
{
if (PanelDic.TryGetValue(token, out var panel))
{
Clear(panel);
}
}
else
{
Clear(GrowlPanel);
}
}
/// <summary>
/// 清除
/// </summary>
/// <param name="panel"></param>
private static void Clear(Panel panel)
{
panel.Children.Clear();
if (panel.ContextMenu != null)
{
panel.ContextMenu.IsOpen = false;
panel.ContextMenu.Opacity = 1;
}
}
private void ButtonCancel_OnClick(object sender, RoutedEventArgs e)
{
if (ActionBeforeClose?.Invoke(false) == true)
{
Close();
}
}
private void ButtonOk_OnClick(object sender, RoutedEventArgs e)
{
if (ActionBeforeClose?.Invoke(true) == true)
{
Close();
}
}
}
}
@@ -1,436 +0,0 @@
using System;
using System.ComponentModel;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using HandyControl.Data;
using HandyControl.Interactivity;
using HandyControl.Tools;
namespace HandyControl.Controls
{
/// <summary>
/// 消息框
/// </summary>
public sealed class MessageBox : Window
{
private MessageBoxResult _messageBoxResult = MessageBoxResult.Cancel;
private bool _showOk;
private bool _showCancel;
private bool _showYes;
private bool _showNo;
public static readonly DependencyProperty MessageProperty = DependencyProperty.Register(
"Message", typeof(string), typeof(MessageBox), new PropertyMetadata(default(string)));
public string Message
{
get => (string) GetValue(MessageProperty);
set => SetValue(MessageProperty, value);
}
public static readonly DependencyProperty ImageProperty = DependencyProperty.Register(
"Image", typeof(Geometry), typeof(MessageBox), new PropertyMetadata(default(Geometry)));
public Geometry Image
{
get => (Geometry) GetValue(ImageProperty);
set => SetValue(ImageProperty, value);
}
public static readonly DependencyProperty ImageBrushProperty = DependencyProperty.Register(
"ImageBrush", typeof(Brush), typeof(MessageBox), new PropertyMetadata(default(Brush)));
public Brush ImageBrush
{
get => (Brush) GetValue(ImageBrushProperty);
set => SetValue(ImageBrushProperty, value);
}
public static readonly DependencyProperty ShowImageProperty = DependencyProperty.Register(
"ShowImage", typeof(bool), typeof(MessageBox), new PropertyMetadata(ValueBoxes.FalseBox));
public bool ShowImage
{
get => (bool) GetValue(ShowImageProperty);
set => SetValue(ShowImageProperty, value);
}
private MessageBox()
{
CommandBindings.Add(new CommandBinding(ControlCommands.Confirm, (s, e) =>
{
_messageBoxResult = MessageBoxResult.OK;
Close();
}, (s, e) => e.CanExecute = _showOk));
CommandBindings.Add(new CommandBinding(ControlCommands.Cancel, (s, e) =>
{
_messageBoxResult = MessageBoxResult.Cancel;
Close();
}, (s, e) => e.CanExecute = _showCancel));
CommandBindings.Add(new CommandBinding(ControlCommands.Yes, (s, e) =>
{
_messageBoxResult = MessageBoxResult.Yes;
Close();
}, (s, e) => e.CanExecute = _showYes));
CommandBindings.Add(new CommandBinding(ControlCommands.No, (s, e) =>
{
_messageBoxResult = MessageBoxResult.No;
Close();
}, (s, e) => e.CanExecute = _showNo));
}
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
base.OnPreviewKeyDown(e);
if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.C)
{
var builder = new StringBuilder();
var line = new string('-', 27);
builder.Append(line);
builder.Append(Environment.NewLine);
builder.Append(Title);
builder.Append(Environment.NewLine);
builder.Append(line);
builder.Append(Environment.NewLine);
builder.Append(Message);
builder.Append(Environment.NewLine);
builder.Append(line);
builder.Append(Environment.NewLine);
if (_showOk)
{
builder.Append(Properties.Langs.Lang.Confirm);
builder.Append(" ");
}
if (_showYes)
{
builder.Append(Properties.Langs.Lang.Yes);
builder.Append(" ");
}
if (_showNo)
{
builder.Append(Properties.Langs.Lang.No);
builder.Append(" ");
}
if (_showCancel)
{
builder.Append(Properties.Langs.Lang.Cancel);
builder.Append(" ");
}
builder.Append(Environment.NewLine);
builder.Append(line);
builder.Append(Environment.NewLine);
Clipboard.SetText(builder.ToString());
}
}
/// <summary>
/// 成功
/// </summary>
/// <param name="messageBoxText"></param>
/// <param name="caption"></param>
public static MessageBoxResult Success(string messageBoxText, string caption = null)
{
MessageBox messageBox = null;
Application.Current.Dispatcher.Invoke(() =>
{
messageBox = CreateMessageBox(null, messageBoxText, caption, MessageBoxButton.OK, MessageBoxImage.None, MessageBoxResult.OK);
SetButtonStatus(messageBox, MessageBoxButton.OK);
messageBox.ShowImage = true;
messageBox.Image = ResourceHelper.GetResource<Geometry>(ResourceToken.SuccessGeometry);
messageBox.ImageBrush = ResourceHelper.GetResource<Brush>(ResourceToken.SuccessBrush);
messageBox.ShowDialog();
});
return messageBox._messageBoxResult;
}
/// <summary>
/// 消息
/// </summary>
/// <param name="messageBoxText"></param>
/// <param name="caption"></param>
public static MessageBoxResult Info(string messageBoxText, string caption = null)
{
MessageBox messageBox = null;
Application.Current.Dispatcher.Invoke(() =>
{
messageBox = CreateMessageBox(null, messageBoxText, caption, MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
SetButtonStatus(messageBox, MessageBoxButton.OK);
SetImage(messageBox, MessageBoxImage.Information);
messageBox.ShowDialog();
});
return messageBox._messageBoxResult;
}
/// <summary>
/// 警告
/// </summary>
/// <param name="messageBoxText"></param>
/// <param name="caption"></param>
public static MessageBoxResult Warning(string messageBoxText, string caption = null)
{
MessageBox messageBox = null;
Application.Current.Dispatcher.Invoke(() =>
{
messageBox = CreateMessageBox(null, messageBoxText, caption, MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK);
SetButtonStatus(messageBox, MessageBoxButton.OK);
SetImage(messageBox, MessageBoxImage.Warning);
messageBox.ShowDialog();
});
return messageBox._messageBoxResult;
}
/// <summary>
/// 错误
/// </summary>
/// <param name="messageBoxText"></param>
/// <param name="caption"></param>
public static MessageBoxResult Error(string messageBoxText, string caption = null)
{
MessageBox messageBox = null;
Application.Current.Dispatcher.Invoke(() =>
{
messageBox = CreateMessageBox(null, messageBoxText, caption, MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
SetButtonStatus(messageBox, MessageBoxButton.OK);
SetImage(messageBox, MessageBoxImage.Error);
messageBox.ShowDialog();
});
return messageBox._messageBoxResult;
}
/// <summary>
/// 严重
/// </summary>
/// <param name="messageBoxText"></param>
/// <param name="caption"></param>
public static MessageBoxResult Fatal(string messageBoxText, string caption = null)
{
MessageBox messageBox = null;
Application.Current.Dispatcher.Invoke(() =>
{
messageBox = CreateMessageBox(null, messageBoxText, caption, MessageBoxButton.OK, MessageBoxImage.None, MessageBoxResult.OK);
SetButtonStatus(messageBox, MessageBoxButton.OK);
messageBox.ShowImage = true;
messageBox.Image = ResourceHelper.GetResource<Geometry>(ResourceToken.FatalGeometry);
messageBox.ImageBrush = ResourceHelper.GetResource<Brush>(ResourceToken.PrimaryTextBrush);
messageBox.ShowDialog();
});
return messageBox._messageBoxResult;
}
/// <summary>
/// 询问
/// </summary>
/// <param name="messageBoxText"></param>
/// <param name="caption"></param>
public static MessageBoxResult Ask(string messageBoxText, string caption = null)
{
MessageBox messageBox = null;
Application.Current.Dispatcher.Invoke(() =>
{
messageBox = CreateMessageBox(null, messageBoxText, caption, MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel);
SetButtonStatus(messageBox, MessageBoxButton.OKCancel);
SetImage(messageBox, MessageBoxImage.Question);
messageBox.ShowDialog();
});
return messageBox._messageBoxResult;
}
/// <summary>
/// 自定义信息展示
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static MessageBoxResult Show(MessageBoxInfo info)
{
MessageBox messageBox = null;
Application.Current.Dispatcher.Invoke(() =>
{
messageBox = CreateMessageBox(null, info.MessageBoxText, info.Caption, info.Button, MessageBoxImage.None, info.DefaultResult);
SetButtonStatus(messageBox, info.Button);
if (!string.IsNullOrEmpty(info.IconKey))
{
messageBox.ShowImage = true;
messageBox.Image = ResourceHelper.GetResource<Geometry>(info.IconKey);
messageBox.ImageBrush = ResourceHelper.GetResource<Brush>(info.IconBrushKey);
}
messageBox.Style = info.Style;
messageBox.ShowDialog();
});
return messageBox._messageBoxResult;
}
/// <summary>
/// 信息展示
/// </summary>
/// <param name="messageBoxText"></param>
/// <param name="caption"></param>
/// <param name="button"></param>
/// <param name="icon"></param>
/// <param name="defaultResult"></param>
/// <returns></returns>
public static MessageBoxResult Show(string messageBoxText, string caption = null,
MessageBoxButton button = MessageBoxButton.OK, MessageBoxImage icon = MessageBoxImage.None,
MessageBoxResult defaultResult = MessageBoxResult.None) =>
Show(null, messageBoxText, caption, button, icon, defaultResult);
/// <summary>
/// 信息展示
/// </summary>
/// <param name="owner"></param>
/// <param name="messageBoxText"></param>
/// <param name="caption"></param>
/// <param name="button"></param>
/// <param name="icon"></param>
/// <param name="defaultResult"></param>
/// <returns></returns>
public static MessageBoxResult Show(System.Windows.Window owner, string messageBoxText, string caption = null, MessageBoxButton button = MessageBoxButton.OK, MessageBoxImage icon = MessageBoxImage.None, MessageBoxResult defaultResult = MessageBoxResult.None)
{
MessageBox messageBox = null;
Application.Current.Dispatcher.Invoke(() =>
{
messageBox = CreateMessageBox(owner, messageBoxText, caption, button, icon, defaultResult);
SetButtonStatus(messageBox, button);
SetImage(messageBox, icon);
messageBox.ShowDialog();
});
return messageBox._messageBoxResult;
}
private static MessageBox CreateMessageBox(
System.Windows.Window owner,
string messageBoxText,
string caption,
MessageBoxButton button,
MessageBoxImage icon,
MessageBoxResult defaultResult)
{
if (!IsValidMessageBoxButton(button))
{
throw new InvalidEnumArgumentException(nameof(button), (int)button, typeof(MessageBoxButton));
}
if (!IsValidMessageBoxImage(icon))
{
throw new InvalidEnumArgumentException(nameof(icon), (int)icon, typeof(MessageBoxImage));
}
if (!IsValidMessageBoxResult(defaultResult))
{
throw new InvalidEnumArgumentException(nameof(defaultResult), (int)defaultResult, typeof(MessageBoxResult));
}
var ownerWindow = owner ?? VisualHelper.GetActiveWindow();
var ownerIsNull = ownerWindow is null;
return new MessageBox
{
Message = messageBoxText,
Owner = ownerWindow,
WindowStartupLocation = WindowStartupLocation.CenterScreen,
ShowTitle = true,
Title = caption ?? string.Empty,
Topmost = ownerIsNull,
_messageBoxResult = defaultResult
};
}
private static void SetButtonStatus(MessageBox messageBox, MessageBoxButton messageBoxButton)
{
switch (messageBoxButton)
{
case MessageBoxButton.OK:
messageBox._showOk = true;
break;
case MessageBoxButton.OKCancel:
messageBox._showOk = true;
messageBox._showCancel = true;
break;
case MessageBoxButton.YesNo:
messageBox._showYes = true;
messageBox._showNo = true;
break;
case MessageBoxButton.YesNoCancel:
messageBox._showYes = true;
messageBox._showNo = true;
messageBox._showCancel = true;
break;
}
}
private static void SetImage(MessageBox messageBox, MessageBoxImage messageBoxImage)
{
var iconKey = string.Empty;
var iconBrushKey = string.Empty;
switch (messageBoxImage)
{
case MessageBoxImage.Error:
iconKey = ResourceToken.ErrorGeometry;
iconBrushKey = ResourceToken.DangerBrush;
break;
case MessageBoxImage.Question:
iconKey = ResourceToken.AskGeometry;
iconBrushKey = ResourceToken.AccentBrush;
break;
case MessageBoxImage.Warning:
iconKey = ResourceToken.WarningGeometry;
iconBrushKey = ResourceToken.WarningBrush;
break;
case MessageBoxImage.Information:
iconKey = ResourceToken.InfoGeometry;
iconBrushKey = ResourceToken.InfoBrush;
break;
}
if (string.IsNullOrEmpty(iconKey)) return;
messageBox.ShowImage = true;
messageBox.Image = ResourceHelper.GetResource<Geometry>(iconKey);
messageBox.ImageBrush = ResourceHelper.GetResource<Brush>(iconBrushKey);
}
private static bool IsValidMessageBoxButton(MessageBoxButton value)
{
return value == MessageBoxButton.OK
|| value == MessageBoxButton.OKCancel
|| value == MessageBoxButton.YesNo
|| value == MessageBoxButton.YesNoCancel;
}
private static bool IsValidMessageBoxImage(MessageBoxImage value)
{
return value == MessageBoxImage.Asterisk
|| value == MessageBoxImage.Error
|| value == MessageBoxImage.Exclamation
|| value == MessageBoxImage.Hand
|| value == MessageBoxImage.Information
|| value == MessageBoxImage.None
|| value == MessageBoxImage.Question
|| value == MessageBoxImage.Stop
|| value == MessageBoxImage.Warning;
}
private static bool IsValidMessageBoxResult(MessageBoxResult value)
{
return value == MessageBoxResult.Cancel
|| value == MessageBoxResult.No
|| value == MessageBoxResult.None
|| value == MessageBoxResult.OK
|| value == MessageBoxResult.Yes;
}
}
}
@@ -116,10 +116,6 @@
<SubType>Designer</SubType>
</Page>
</ItemGroup>
<ItemGroup>
<Compile Include="Controls\Other\Growl.cs" />
<Compile Include="Controls\Window\MessageBox.cs" />
</ItemGroup>
<Import Project="..\..\Shared\HandyControl_Shared\HandyControl_Shared.projitems" Label="Shared" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>