修改 主程序下的Comm文件夹 转到 Frameork中

This commit is contained in:
chfei committed 2026-10-17 18:16:55 +08:00
1 parent 2f9c98b105
commit 1eb5315261
78 files changed
+274 -227

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
using System.Windows.Markup;
[assembly: XmlnsDefinition("WxOrder.Framework", "WxOrder.Framework")]
[assembly: XmlnsDefinition("WxOrder.Framework", "WxOrder.Framework.Commons")]
[assembly: XmlnsPrefix("WxOrder.Framework", "of")]
@@ -0,0 +1,244 @@
using System.Linq.Expressions;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Reflection.Emit;
using System.Resources;
namespace WxOrder.Framework.Commons
{
/// <summary>
/// Provides an implementation of the <see cref="IAsyncCommand"/>
/// </summary>
public class AsyncDelegateCommand : DelegateCommandBase, IAsyncCommand
{
private bool _enableParallelExecution = false;
private bool _isExecuting = false;
private readonly Func<CancellationToken, Task> _executeMethod;
private Func<bool> _canExecuteMethod;
private Func<CancellationToken> _getCancellationToken = () => CancellationToken.None;
/// <summary>
/// Creates a new instance of <see cref="AsyncDelegateCommand"/> with the <see cref="Func{Task}"/> to invoke on execution.
/// </summary>
/// <param name="executeMethod">The <see cref="Func{Task}"/> to invoke when <see cref="ICommand.Execute(object)"/> is called.</param>
public AsyncDelegateCommand(Func<Task> executeMethod)
#if NET6_0_OR_GREATER
: this (c => executeMethod().WaitAsync(c), () => true)
#else
: this(c => executeMethod(), () => true)
#endif
{
}
/// <summary>
/// Creates a new instance of <see cref="AsyncDelegateCommand"/> with the <see cref="Func{Task}"/> to invoke on execution.
/// </summary>
/// <param name="executeMethod">The <see cref="Func{CancellationToken, Task}"/> to invoke when <see cref="ICommand.Execute(object)"/> is called.</param>
public AsyncDelegateCommand(Func<CancellationToken, Task> executeMethod)
: this(executeMethod, () => true)
{
}
/// <summary>
/// Creates a new instance of <see cref="DelegateCommand"/> with the <see cref="Func{Task}"/> to invoke on execution
/// and a <see langword="Func" /> to query for determining if the command can execute.
/// </summary>
/// <param name="executeMethod">The <see cref="Func{Task}"/> to invoke when <see cref="ICommand.Execute"/> is called.</param>
/// <param name="canExecuteMethod">The delegate to invoke when <see cref="ICommand.CanExecute"/> is called</param>
public AsyncDelegateCommand(Func<Task> executeMethod, Func<bool> canExecuteMethod)
#if NET6_0_OR_GREATER
: this(c => executeMethod().WaitAsync(c), canExecuteMethod)
#else
: this(c => executeMethod(), canExecuteMethod)
#endif
{
}
/// <summary>
/// Creates a new instance of <see cref="DelegateCommand"/> with the <see cref="Func{Task}"/> to invoke on execution
/// and a <see langword="Func" /> to query for determining if the command can execute.
/// </summary>
/// <param name="executeMethod">The <see cref="Func{CancellationToken, Task}"/> to invoke when <see cref="ICommand.Execute"/> is called.</param>
/// <param name="canExecuteMethod">The delegate to invoke when <see cref="ICommand.CanExecute"/> is called</param>
public AsyncDelegateCommand(Func<CancellationToken, Task> executeMethod, Func<bool> canExecuteMethod)
: base()
{
if (executeMethod == null || canExecuteMethod == null)
throw new ArgumentNullException(nameof(executeMethod), "Neither the executeMethod nor the canExecuteMethod delegates can be null");
_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
}
/// <summary>
/// Gets the current state of the AsyncDelegateCommand
/// </summary>
public bool IsExecuting
{
get => _isExecuting;
private set
{
_isExecuting = value;
OnCanExecuteChanged();
}
}
///<summary>
/// Executes the command.
///</summary>
public async Task Execute(CancellationToken? cancellationToken = null)
{
var token = cancellationToken ?? _getCancellationToken();
try
{
if (!_enableParallelExecution && IsExecuting)
return;
IsExecuting = true;
await _executeMethod(token)
.ConfigureAwait(false);
}
catch
{
throw;
}
finally
{
IsExecuting = false;
}
}
/// <summary>
/// Determines if the command can be executed.
/// </summary>
/// <returns>Returns <see langword="true"/> if the command can execute,otherwise returns <see langword="false"/>.</returns>
public bool CanExecute()
{
try
{
if (!_enableParallelExecution && IsExecuting)
return false;
return _canExecuteMethod?.Invoke() ?? true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// Handle the internal invocation of <see cref="ICommand.Execute(object)"/>
/// </summary>
/// <param name="parameter">Command Parameter</param>
protected override async void Execute(object parameter)
{
// We don't want to wrap this in a try/catch because we already handle
// or mean to rethrow the exception in the call with the CancellationToken.
var cancellationToken = _getCancellationToken();
await Execute(cancellationToken)
.ConfigureAwait(false);
}
/// <summary>
/// Handle the internal invocation of <see cref="ICommand.CanExecute(object)"/>
/// </summary>
/// <param name="parameter"></param>
/// <returns><see langword="true"/> if the Command Can Execute, otherwise <see langword="false" /></returns>
protected override bool CanExecute(object parameter)
{
return CanExecute();
}
/// <summary>
/// Enables Parallel Execution of Async Tasks
/// </summary>
/// <returns>The current instance of <see cref="AsyncDelegateCommand"/>.</returns>
public AsyncDelegateCommand EnableParallelExecution()
{
_enableParallelExecution = true;
return this;
}
/// <summary>
/// Sets the <see cref="CancellationTokenSourceFactory(Func{CancellationToken})"/> based on the specified timeout.
/// </summary>
/// <param name="timeout">A specified timeout.</param>
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
public AsyncDelegateCommand CancelAfter(TimeSpan timeout) =>
CancellationTokenSourceFactory(() => new CancellationTokenSource(timeout).Token);
/// <summary>
/// Provides a delegate callback to provide a default CancellationToken when the Command is invoked.
/// </summary>
/// <param name="factory">The default <see cref="CancellationToken"/> Factory.</param>
/// <returns>The current instance of <see cref="AsyncDelegateCommand"/>.</returns>
public AsyncDelegateCommand CancellationTokenSourceFactory(Func<CancellationToken> factory)
{
_getCancellationToken = factory;
return this;
}
/// <summary>
/// Observes a property that implements INotifyPropertyChanged, and automatically calls DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications.
/// </summary>
/// <typeparam name="T">The object type containing the property specified in the expression.</typeparam>
/// <param name="propertyExpression">The property expression. Example: ObservesProperty(() => PropertyName).</param>
/// <returns>The current instance of <see cref="AsyncDelegateCommand"/>.</returns>
public AsyncDelegateCommand ObservesProperty<T>(Expression<Func<T>> propertyExpression)
{
ObservesPropertyInternal(propertyExpression);
return this;
}
/// <summary>
/// Observes a property that is used to determine if this command can execute, and if it implements INotifyPropertyChanged it will automatically call DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications.
/// </summary>
/// <param name="canExecuteExpression">The property expression. Example: ObservesCanExecute(() => PropertyName).</param>
/// <returns>The current instance of <see cref="AsyncDelegateCommand"/>.</returns>
public AsyncDelegateCommand ObservesCanExecute(Expression<Func<bool>> canExecuteExpression)
{
_canExecuteMethod = canExecuteExpression.Compile();
ObservesPropertyInternal(canExecuteExpression);
return this;
}
/// <summary>
/// Provides the ability to connect a delegate to catch exceptions encountered by CanExecute or the Execute methods of the DelegateCommand
/// </summary>
/// <param name="catch">TThe callback when a specific exception is encountered</param>
/// <returns>The current instance of <see cref="AsyncDelegateCommand"/>.</returns>
public AsyncDelegateCommand Catch<TException>(Action<TException> @catch)
where TException : Exception
{
return this;
}
/// <summary>
/// Provides the ability to connect a delegate to catch exceptions encountered by CanExecute or the Execute methods of the DelegateCommand
/// </summary>
/// <param name="catch">The generic / default callback when an exception is encountered</param>
/// <returns>The current instance of <see cref="AsyncDelegateCommand"/>.</returns>
public AsyncDelegateCommand Catch(Action<Exception> @catch)
{
return this;
}
Task IAsyncCommand.ExecuteAsync(object parameter)
{
return Execute(_getCancellationToken());
}
Task IAsyncCommand.ExecuteAsync(object parameter, CancellationToken cancellationToken)
{
return Execute(cancellationToken);
}
}
}
@@ -0,0 +1,284 @@
using System.Linq.Expressions;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Reflection.Emit;
using System.Resources;
namespace WxOrder.Framework.Commons
{
/// <summary>
/// Provides an implementation of the <see cref="IAsyncCommand"/> with a generic parameter type.
/// </summary>
/// <typeparam name="T"></typeparam>
public class AsyncDelegateCommand<T> : DelegateCommandBase, IAsyncCommand
{
private bool _enableParallelExecution = false;
private bool _isExecuting = false;
private readonly Func<T, CancellationToken, Task> _executeMethod;
private Func<T, bool> _canExecuteMethod;
private Func<CancellationToken> _getCancellationToken = () => CancellationToken.None;
/// <summary>
/// Creates a new instance of <see cref="AsyncDelegateCommand{T}"/> with the <see cref="Func{Task}"/> to invoke on execution.
/// </summary>
/// <param name="executeMethod">The <see cref="Func{T, Task}"/> to invoke when <see cref="ICommand.Execute(object)"/> is called.</param>
public AsyncDelegateCommand(Func<T, Task> executeMethod)
#if NET6_0_OR_GREATER
: this((p,t) => executeMethod(p).WaitAsync(t), _ => true)
#else
: this((p, t) => executeMethod(p), _ => true)
#endif
{
}
/// <summary>
/// Creates a new instance of <see cref="AsyncDelegateCommand{T}"/> with the <see cref="Func{Task}"/> to invoke on execution.
/// </summary>
/// <param name="executeMethod">The <see cref="Func{T, CancellationToken, Task}"/> to invoke when <see cref="ICommand.Execute(object)"/> is called.</param>
public AsyncDelegateCommand(Func<T, CancellationToken, Task> executeMethod)
: this(executeMethod, _ => true)
{
}
/// <summary>
/// Creates a new instance of <see cref="DelegateCommand"/> with the <see cref="Func{Task}"/> to invoke on execution
/// and a <see langword="Func" /> to query for determining if the command can execute.
/// </summary>
/// <param name="executeMethod">The <see cref="Func{T, Task}"/> to invoke when <see cref="ICommand.Execute"/> is called.</param>
/// <param name="canExecuteMethod">The delegate to invoke when <see cref="ICommand.CanExecute"/> is called</param>
public AsyncDelegateCommand(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod)
#if NET6_0_OR_GREATER
: this((p, c) => executeMethod(p).WaitAsync(c), canExecuteMethod)
#else
: this((p, c) => executeMethod(p), canExecuteMethod)
#endif
{
}
/// <summary>
/// Creates a new instance of <see cref="DelegateCommand"/> with the <see cref="Func{Task}"/> to invoke on execution
/// and a <see langword="Func" /> to query for determining if the command can execute.
/// </summary>
/// <param name="executeMethod">The <see cref="Func{T, CancellationToken, Task}"/> to invoke when <see cref="ICommand.Execute"/> is called.</param>
/// <param name="canExecuteMethod">The delegate to invoke when <see cref="ICommand.CanExecute"/> is called</param>
public AsyncDelegateCommand(Func<T, CancellationToken, Task> executeMethod, Func<T, bool> canExecuteMethod)
: base()
{
if (executeMethod == null || canExecuteMethod == null)
throw new ArgumentNullException(nameof(executeMethod), "Neither the executeMethod nor the canExecuteMethod delegates can be null");
_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
}
/// <summary>
/// Gets the current state of the AsyncDelegateCommand
/// </summary>
public bool IsExecuting
{
get => _isExecuting;
private set
{
_isExecuting = value;
OnCanExecuteChanged();
}
}
///<summary>
/// Executes the command.
///</summary>
public async Task Execute(T parameter, CancellationToken? cancellationToken = null)
{
var token = cancellationToken ?? _getCancellationToken();
try
{
if (!_enableParallelExecution && IsExecuting)
return;
IsExecuting = true;
await _executeMethod(parameter, token)
.ConfigureAwait(false);
}
catch (Exception ex)
{
throw;
}
finally
{
IsExecuting = false;
}
}
/// <summary>
/// Determines if the command can be executed.
/// </summary>
/// <returns>Returns <see langword="true"/> if the command can execute,otherwise returns <see langword="false"/>.</returns>
public bool CanExecute(T parameter)
{
try
{
if (!_enableParallelExecution && IsExecuting)
return false;
return _canExecuteMethod?.Invoke(parameter) ?? true;
}
catch (Exception ex)
{
throw;
return false;
}
}
/// <summary>
/// Handle the internal invocation of <see cref="ICommand.Execute(object)"/>
/// </summary>
/// <param name="parameter">Command Parameter</param>
protected override async void Execute(object parameter)
{
var cancellationToken = _getCancellationToken();
T parameterAsT;
try
{
parameterAsT = (T)parameter;
}
catch (Exception ex)
{
throw;
}
// If we had an exception casting the parameter to T ,
// we would have already returned. We want to surface any
// exceptions thrown by the Execute method.
await Execute(parameterAsT, cancellationToken)
.ConfigureAwait(false);
}
/// <summary>
/// Handle the internal invocation of <see cref="ICommand.CanExecute(object)"/>
/// </summary>
/// <param name="parameter"></param>
/// <returns><see langword="true"/> if the Command Can Execute, otherwise <see langword="false" /></returns>
protected override bool CanExecute(object parameter)
{
try
{
return CanExecute((T)parameter);
}
catch (Exception ex)
{
throw;
}
}
/// <summary>
/// Enables Parallel Execution of Async Tasks
/// </summary>
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
public AsyncDelegateCommand<T> EnableParallelExecution()
{
_enableParallelExecution = true;
return this;
}
/// <summary>
/// Sets the <see cref="CancellationTokenSourceFactory(Func{CancellationToken})"/> based on the specified timeout.
/// </summary>
/// <param name="timeout">A specified timeout.</param>
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
public AsyncDelegateCommand<T> CancelAfter(TimeSpan timeout) =>
CancellationTokenSourceFactory(() => new CancellationTokenSource(timeout).Token);
/// <summary>
/// Provides a delegate callback to provide a default CancellationToken when the Command is invoked.
/// </summary>
/// <param name="factory">The default <see cref="CancellationToken"/> Factory.</param>
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
public AsyncDelegateCommand<T> CancellationTokenSourceFactory(Func<CancellationToken> factory)
{
_getCancellationToken = factory;
return this;
}
/// <summary>
/// Observes a property that implements INotifyPropertyChanged, and automatically calls DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications.
/// </summary>
/// <typeparam name="TType">The type of the return value of the method that this delegate encapsulates</typeparam>
/// <param name="propertyExpression">The property expression. Example: ObservesProperty(() => PropertyName).</param>
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
public AsyncDelegateCommand<T> ObservesProperty<TType>(Expression<Func<TType>> propertyExpression)
{
ObservesPropertyInternal(propertyExpression);
return this;
}
/// <summary>
/// Observes a property that is used to determine if this command can execute, and if it implements INotifyPropertyChanged it will automatically call DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications.
/// </summary>
/// <param name="canExecuteExpression">The property expression. Example: ObservesCanExecute(() => PropertyName).</param>
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
public AsyncDelegateCommand<T> ObservesCanExecute(Expression<Func<bool>> canExecuteExpression)
{
Expression<Func<T, bool>> expression = Expression.Lambda<Func<T, bool>>(canExecuteExpression.Body, Expression.Parameter(typeof(T), "o"));
_canExecuteMethod = expression.Compile();
ObservesPropertyInternal(canExecuteExpression);
return this;
}
/// <summary>
/// Provides the ability to connect a delegate to catch exceptions encountered by CanExecute or the Execute methods of the DelegateCommand
/// </summary>
/// <param name="catch">TThe callback when a specific exception is encountered</param>
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
public AsyncDelegateCommand<T> Catch<TException>(Action<TException> @catch)
where TException : Exception
{
return this;
}
/// <summary>
/// Provides the ability to connect a delegate to catch exceptions encountered by CanExecute or the Execute methods of the DelegateCommand
/// </summary>
/// <param name="catch">The generic / default callback when an exception is encountered</param>
/// <returns>The current instance of <see cref="AsyncDelegateCommand{T}"/>.</returns>
public AsyncDelegateCommand<T> Catch(Action<Exception> @catch)
{
return this;
}
async Task IAsyncCommand.ExecuteAsync(object parameter)
{
try
{
// If T is not nullable this may throw an exception
await Execute((T)parameter, _getCancellationToken());
}
catch (Exception ex)
{
throw;
}
}
async Task IAsyncCommand.ExecuteAsync(object parameter, CancellationToken cancellationToken)
{
try
{
// If T is not nullable this may throw an exception
await Execute((T)parameter, cancellationToken);
}
catch (Exception ex)
{
throw;
}
}
}
}
@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WxOrder.Framework.Commons
{
public static class DebugVisibility
{
// 定义一个附加属性
public static readonly DependencyProperty EnableProperty =
DependencyProperty.RegisterAttached(
"Enable",
typeof(bool),
typeof(DebugVisibility),
new FrameworkPropertyMetadata(
true, FrameworkPropertyMetadataOptions.AffectsArrange,
OnEnableChanged, OnEnableCoerceCall));
private static object OnEnableCoerceCall(DependencyObject d, object baseValue)
{
if (d is UIElement element)
{
#if DEBUG
// Debug 模式下,根据属性值决定可见性
element.Visibility = (bool)baseValue ? Visibility.Visible : Visibility.Collapsed;
#else
// Release 模式下,隐藏所有标记了 IsDebug 的元素
element.Visibility = Visibility.Collapsed;
#endif
}
return baseValue;
}
private static void OnEnableChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is UIElement element)
{
#if DEBUG
// Debug 模式下,根据属性值决定可见性
element.Visibility = (bool)e.NewValue ? Visibility.Visible : Visibility.Collapsed;
#else
// Release 模式下,隐藏所有标记了 IsDebug 的元素
element.Visibility = Visibility.Collapsed;
#endif
}
}
public static bool GetEnable(DependencyObject obj) => (bool)obj.GetValue(EnableProperty);
public static void SetEnable(DependencyObject obj, bool value) => obj.SetValue(EnableProperty, value);
}
}
@@ -0,0 +1,103 @@
using System;
using System.Linq.Expressions;
using System.Windows.Input;
namespace WxOrder.Framework.Commons
{
/// <summary>
/// An <see cref="ICommand"/> whose delegates do not take any parameters for <see cref="Execute()"/> and <see cref="CanExecute()"/>.
/// </summary>
/// <see cref="DelegateCommandBase"/>
/// <see cref="DelegateCommand{T}"/>
public class DelegateCommand : DelegateCommandBase
{
Action _executeMethod;
Func<bool> _canExecuteMethod;
/// <summary>
/// Creates a new instance of <see cref="DelegateCommand"/> with the <see cref="Action"/> to invoke on execution.
/// </summary>
/// <param name="executeMethod">The <see cref="Action"/> to invoke when <see cref="ICommand.Execute(object)"/> is called.</param>
public DelegateCommand(Action executeMethod)
: this(executeMethod, () => true)
{
}
/// <summary>
/// Creates a new instance of <see cref="DelegateCommand"/> with the <see cref="Action"/> to invoke on execution
/// and a <see langword="Func" /> to query for determining if the command can execute.
/// </summary>
/// <param name="executeMethod">The <see cref="Action"/> to invoke when <see cref="ICommand.Execute"/> is called.</param>
/// <param name="canExecuteMethod">The <see cref="Func{TResult}"/> to invoke when <see cref="ICommand.CanExecute"/> is called</param>
public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod)
: base()
{
if (executeMethod == null || canExecuteMethod == null)
throw new ArgumentNullException(nameof(executeMethod), "Delegate Command Delegates Cannot Be Null");
_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
}
///<summary>
/// Executes the command.
///</summary>
public void Execute()
{
_executeMethod();
}
/// <summary>
/// Determines if the command can be executed.
/// </summary>
/// <returns>Returns <see langword="true"/> if the command can execute,otherwise returns <see langword="false"/>.</returns>
public bool CanExecute()
{
return _canExecuteMethod();
}
/// <summary>
/// Handle the internal invocation of <see cref="ICommand.Execute(object)"/>
/// </summary>
/// <param name="parameter">Command Parameter</param>
protected override void Execute(object parameter)
{
Execute();
}
/// <summary>
/// Handle the internal invocation of <see cref="ICommand.CanExecute(object)"/>
/// </summary>
/// <param name="parameter"></param>
/// <returns><see langword="true"/> if the Command Can Execute, otherwise <see langword="false" /></returns>
protected override bool CanExecute(object parameter)
{
return CanExecute();
}
/// <summary>
/// Observes a property that implements INotifyPropertyChanged, and automatically calls DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications.
/// </summary>
/// <typeparam name="T">The object type containing the property specified in the expression.</typeparam>
/// <param name="propertyExpression">The property expression. Example: ObservesProperty(() => PropertyName).</param>
/// <returns>The current instance of DelegateCommand</returns>
public DelegateCommand ObservesProperty<T>(Expression<Func<T>> propertyExpression)
{
ObservesPropertyInternal(propertyExpression);
return this;
}
/// <summary>
/// Observes a property that is used to determine if this command can execute, and if it implements INotifyPropertyChanged it will automatically call DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications.
/// </summary>
/// <param name="canExecuteExpression">The property expression. Example: ObservesCanExecute(() => PropertyName).</param>
/// <returns>The current instance of DelegateCommand</returns>
public DelegateCommand ObservesCanExecute(Expression<Func<bool>> canExecuteExpression)
{
_canExecuteMethod = canExecuteExpression.Compile();
ObservesPropertyInternal(canExecuteExpression);
return this;
}
}
}
@@ -0,0 +1,135 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
namespace WxOrder.Framework.Commons
{
public abstract class DelegateCommandBase : ICommand
{
private bool _isActive;
private SynchronizationContext _synchronizationContext;
private readonly HashSet<string> _observedPropertiesExpressions = new HashSet<string>();
/// <summary>
/// Creates a new instance of a <see cref="DelegateCommandBase"/>, specifying both the execute action and the can execute function.
/// </summary>
protected DelegateCommandBase()
{
_synchronizationContext = SynchronizationContext.Current;
}
/// <summary>
/// Occurs when changes occur that affect whether or not the command should execute.
/// </summary>
public virtual event EventHandler CanExecuteChanged;
/// <summary>
/// Raises <see cref="ICommand.CanExecuteChanged"/> so every
/// command invoker can requery <see cref="ICommand.CanExecute"/>.
/// </summary>
protected virtual void OnCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
{
if (_synchronizationContext != null && _synchronizationContext != SynchronizationContext.Current)
_synchronizationContext.Post((o) => handler.Invoke(this, EventArgs.Empty), null);
else
handler.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Raises <see cref="CanExecuteChanged"/> so every command invoker
/// can requery to check if the command can execute.
/// </summary>
/// <remarks>Note that this will trigger the execution of <see cref="CanExecuteChanged"/> once for each invoker.</remarks>
[SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
public void RaiseCanExecuteChanged()
{
OnCanExecuteChanged();
}
void ICommand.Execute(object parameter)
{
Execute(parameter);
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter);
}
/// <summary>
/// Handle the internal invocation of <see cref="ICommand.Execute(object)"/>
/// </summary>
/// <param name="parameter">Command Parameter</param>
protected abstract void Execute(object parameter);
/// <summary>
/// Handle the internal invocation of <see cref="ICommand.CanExecute(object)"/>
/// </summary>
/// <param name="parameter"></param>
/// <returns><see langword="true"/> if the Command Can Execute, otherwise <see langword="false" /></returns>
protected abstract bool CanExecute(object parameter);
/// <summary>
/// Observes a property that implements INotifyPropertyChanged, and automatically calls DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications.
/// </summary>
/// <typeparam name="T">The object type containing the property specified in the expression.</typeparam>
/// <param name="propertyExpression">The property expression. Example: ObservesProperty(() => PropertyName).</param>
protected internal void ObservesPropertyInternal<T>(Expression<Func<T>> propertyExpression)
{
if (_observedPropertiesExpressions.Contains(propertyExpression.ToString()))
{
throw new ArgumentException($"{propertyExpression.ToString()} is already being observed.",
nameof(propertyExpression));
}
else
{
_observedPropertiesExpressions.Add(propertyExpression.ToString());
}
}
#region IsActive
/// <summary>
/// Gets or sets a value indicating whether the object is active.
/// </summary>
/// <value><see langword="true" /> if the object is active; otherwise <see langword="false" />.</value>
public bool IsActive
{
get { return _isActive; }
set
{
if (_isActive != value)
{
_isActive = value;
OnIsActiveChanged();
}
}
}
/// <summary>
/// Fired if the <see cref="IsActive"/> property changes.
/// </summary>
public virtual event EventHandler IsActiveChanged;
/// <summary>
/// This raises the <see cref="DelegateCommandBase.IsActiveChanged"/> event.
/// </summary>
protected virtual void OnIsActiveChanged()
{
IsActiveChanged?.Invoke(this, EventArgs.Empty);
}
#endregion
}
}
@@ -0,0 +1,119 @@
using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Windows.Input;
namespace WxOrder.Framework.Commons
{
public class DelegateCommand<T> : DelegateCommandBase
{
readonly Action<T> _executeMethod;
Func<T, bool> _canExecuteMethod;
/// <summary>
/// Initializes a new instance of <see cref="DelegateCommand{T}"/>.
/// </summary>
/// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param>
/// <remarks><see cref="CanExecute(T)"/> will always return true.</remarks>
public DelegateCommand(Action<T> executeMethod)
: this(executeMethod, (o) => true)
{
}
/// <summary>
/// Initializes a new instance of <see cref="DelegateCommand{T}"/>.
/// </summary>
/// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param>
/// <param name="canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param>
/// <exception cref="ArgumentNullException">When both <paramref name="executeMethod"/> and <paramref name="canExecuteMethod"/> are <see langword="null" />.</exception>
public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
: base()
{
if (executeMethod == null || canExecuteMethod == null)
throw new ArgumentNullException(nameof(executeMethod), "Delegate Command Delegates Cannot Be Null");
TypeInfo genericTypeInfo = typeof(T).GetTypeInfo();
// DelegateCommand allows object or Nullable<>.
// note: Nullable<> is a struct so we cannot use a class constraint.
if (genericTypeInfo.IsValueType)
{
if (!genericTypeInfo.IsGenericType || !typeof(Nullable<>).GetTypeInfo().IsAssignableFrom(genericTypeInfo.GetGenericTypeDefinition().GetTypeInfo()))
{
throw new InvalidCastException("Delegate CommandInvalid Generic Payload Type");
}
}
_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
}
///<summary>
///Executes the command and invokes the <see cref="Action{T}"/> provided during construction.
///</summary>
///<param name="parameter">Data used by the command.</param>
public void Execute(T parameter)
{
_executeMethod(parameter);
}
///<summary>
///Determines if the command can execute by invoked the <see cref="Func{T,Bool}"/> provided during construction.
///</summary>
///<param name="parameter">Data used by the command to determine if it can execute.</param>
///<returns>
///<see langword="true" /> if this command can be executed; otherwise, <see langword="false" />.
///</returns>
public bool CanExecute(T parameter)
{
return _canExecuteMethod(parameter);
}
/// <summary>
/// Handle the internal invocation of <see cref="ICommand.Execute(object)"/>
/// </summary>
/// <param name="parameter">Command Parameter</param>
protected override void Execute(object parameter)
{
Execute((T)parameter);
}
/// <summary>
/// Handle the internal invocation of <see cref="ICommand.CanExecute(object)"/>
/// </summary>
/// <param name="parameter"></param>
/// <returns><see langword="true"/> if the Command Can Execute, otherwise <see langword="false" /></returns>
protected override bool CanExecute(object parameter)
{
return CanExecute((T)parameter);
}
/// <summary>
/// Observes a property that implements INotifyPropertyChanged, and automatically calls DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications.
/// </summary>
/// <typeparam name="TType">The type of the return value of the method that this delegate encapsulates</typeparam>
/// <param name="propertyExpression">The property expression. Example: ObservesProperty(() => PropertyName).</param>
/// <returns>The current instance of DelegateCommand</returns>
public DelegateCommand<T> ObservesProperty<TType>(Expression<Func<TType>> propertyExpression)
{
ObservesPropertyInternal(propertyExpression);
return this;
}
/// <summary>
/// Observes a property that is used to determine if this command can execute, and if it implements INotifyPropertyChanged it will automatically call DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications.
/// </summary>
/// <param name="canExecuteExpression">The property expression. Example: ObservesCanExecute(() => PropertyName).</param>
/// <returns>The current instance of DelegateCommand</returns>
public DelegateCommand<T> ObservesCanExecute(Expression<Func<bool>> canExecuteExpression)
{
Expression<Func<T, bool>> expression = Expression.Lambda<Func<T, bool>>(canExecuteExpression.Body, Expression.Parameter(typeof(T), "o"));
_canExecuteMethod = expression.Compile();
ObservesPropertyInternal(canExecuteExpression);
return this;
}
}
}
@@ -0,0 +1,23 @@
<Window
x:Class="WxOrder.Framework.Commons.DialogWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WxOrder.Framework.Commons"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="{Binding Title}"
d:DesignHeight="450"
d:DesignWidth="800"
Background="#FFFFFF"
WindowStartupLocation="CenterOwner"
mc:Ignorable="d">
<Window.Resources>
<Style x:Key="DialogWindowStyle" TargetType="Window">
<Setter Property="Tag" Value="Default" />
<Setter Property="ResizeMode" Value="NoResize" />
<Setter Property="ShowInTaskbar" Value="False" />
<Setter Property="WindowChrome.GlassFrameThickness" Value="-1" />
</Style>
</Window.Resources>
<Grid />
</Window>
@@ -0,0 +1,129 @@
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Contexts;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using WxOrder.Framework.Commons;
using WxOrder.Framework.Commons.Dialogs;
namespace WxOrder.Framework.Commons
{
/// <summary>
/// DialogWindow.xaml 的交互逻辑
/// </summary>
public partial class DialogWindow : Window, IDialogWindow
{
private readonly Style dialogWindowStyle;
private bool isConstructorSuccessful = false;
private UserControl _content;
public DialogWindow(Window owner = null)
{
InitializeComponent();
Owner = owner ?? Application.Current.MainWindow;
isConstructorSuccessful = true;
dialogWindowStyle = (Style)TryFindResource("DialogWindowStyle");
Loaded += DialogWindow_Loaded;
}
private void DialogWindow_Loaded(object sender, RoutedEventArgs e)
{
Loaded -= DialogWindow_Loaded;
}
protected override void OnContentChanged(object oldContent, object newContent)
{
this.Style = dialogWindowStyle;
if (newContent is System.Windows.Controls.UserControl control)
{
_content = control;
Setter widthSetter = this.Style.Setters.OfType<Setter>().FirstOrDefault(a => a.Property == WidthProperty);
if (widthSetter == null)
{
if (double.IsNaN(control.Width))
{
this.Width = DialogWindowProperty.GetWidth(control);
}
else
{
this.Width = control.Width;
control.Width = double.NaN;
}
}
Setter heightSetter = this.Style.Setters.OfType<Setter>().FirstOrDefault(a => a.Property == HeightProperty);
if (heightSetter == null)
{
if (double.IsNaN(control.Height))
{
this.Height = DialogWindowProperty.GetHeight(control);
}
else
{
this.Height = control.Height;
control.Height = double.NaN;
}
}
ResizeMode resizeExt = DialogWindowProperty.GetResizeMode(control);
if (resizeExt != ResizeMode.CanResize)
{
this.ResizeMode = resizeExt;
}
WindowStyle wstyleExt = DialogWindowProperty.GetWindowStyle(control);
if (wstyleExt != WindowStyle.SingleBorderWindow)
{
this.WindowStyle = wstyleExt;
}
}
base.OnContentChanged(oldContent, newContent);
}
protected override void OnStyleChanged(Style oldStyle, Style newStyle)
{
if (newStyle.TargetType == typeof(Window))
{
if (isConstructorSuccessful)
{
//dialogWindowStyle.Merge(newStyle);
}
return;
}
base.OnStyleChanged(oldStyle, newStyle);
}
#region ShowMiniButton
private const int GWL_STYLE = -16;
private const int WS_MINIMIZEBOX = 0x00020000;
public IDialogResult Result { get; set; }
[DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
var hwnd = new WindowInteropHelper(this).Handle;
int style = GetWindowLong(hwnd, GWL_STYLE);
style &= ~WS_MINIMIZEBOX;
if (DialogWindowProperty.GetShowMinButton(this._content) == false)
{
SetWindowLong(hwnd, GWL_STYLE, style);
}
}
#endregion
}
}
@@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WxOrder.Framework.Commons
{
/// <summary>
/// 弹出窗口属性值
/// </summary>
public class DialogWindowProperty
{
public static readonly DependencyProperty WindowStartupLocationProperty = DependencyProperty.RegisterAttached(
"WindowStartupLocation", typeof(WindowStartupLocation), typeof(DialogWindowProperty), new PropertyMetadata(WindowStartupLocation.CenterScreen));
public static void SetWindowStartupLocation(DependencyObject element, WindowStartupLocation value)
=> element.SetValue(WindowStartupLocationProperty, value);
public static WindowStartupLocation GetWindowStartupLocation(DependencyObject element)
=> (WindowStartupLocation)element.GetValue(WindowStartupLocationProperty);
public static readonly DependencyProperty ResizeModeProperty = DependencyProperty.RegisterAttached(
"ResizeMode", typeof(ResizeMode), typeof(DialogWindowProperty), new PropertyMetadata(ResizeMode.CanResize));
public static void SetResizeMode(DependencyObject element, ResizeMode value)
=> element.SetValue(ResizeModeProperty, value);
public static ResizeMode GetResizeMode(DependencyObject element)
=> (ResizeMode)element.GetValue(ResizeModeProperty);
public static readonly DependencyProperty WindowStyleProperty =
DependencyProperty.RegisterAttached(
"WindowStyle",
typeof(WindowStyle),
typeof(DialogWindowProperty),
new PropertyMetadata(WindowStyle.SingleBorderWindow));
public static void SetWindowStyle(DependencyObject element, WindowStyle value)
=> element.SetValue(WindowStyleProperty, value);
public static WindowStyle GetWindowStyle(DependencyObject element)
=> (WindowStyle)element.GetValue(WindowStyleProperty);
public static readonly DependencyProperty WidthProperty = DependencyProperty.RegisterAttached(
"Width", typeof(double), typeof(DialogWindowProperty), new PropertyMetadata(double.NaN));
public static void SetWidth(DependencyObject element, double value)
=> element.SetValue(WidthProperty, value);
public static double GetWidth(DependencyObject element)
=> (double)element.GetValue(WidthProperty);
public static readonly DependencyProperty HeightProperty = DependencyProperty.RegisterAttached(
"Height", typeof(double), typeof(DialogWindowProperty), new PropertyMetadata(double.NaN));
public static void SetHeight(DependencyObject element, double value)
=> element.SetValue(HeightProperty, value);
public static double GetHeight(DependencyObject element)
=> (double)element.GetValue(HeightProperty);
// 1. ShowMinButton 附加属性
public static readonly DependencyProperty ShowMinButtonProperty =
DependencyProperty.RegisterAttached(
"ShowMinButton",
typeof(bool),
typeof(DialogWindowProperty),
new PropertyMetadata(true));
public static void SetShowMinButton(DependencyObject element, bool value)
=> element.SetValue(ShowMinButtonProperty, value);
public static bool GetShowMinButton(DependencyObject element)
=> (bool)element.GetValue(ShowMinButtonProperty);
// 2. ShowMaxButton 附加属性
public static readonly DependencyProperty ShowMaxButtonProperty =
DependencyProperty.RegisterAttached(
"ShowMaxButton",
typeof(bool),
typeof(DialogWindowProperty),
new PropertyMetadata(true));
public static void SetShowMaxButton(DependencyObject element, bool value)
=> element.SetValue(ShowMaxButtonProperty, value);
public static bool GetShowMaxButton(DependencyObject element)
=> (bool)element.GetValue(ShowMaxButtonProperty);
// 3. ShowCloseButton 附加属性
public static readonly DependencyProperty ShowCloseButtonProperty =
DependencyProperty.RegisterAttached(
"ShowCloseButton",
typeof(bool),
typeof(DialogWindowProperty),
new PropertyMetadata(true));
public static void SetShowCloseButton(DependencyObject element, bool value)
=> element.SetValue(ShowCloseButtonProperty, value);
public static bool GetShowCloseButton(DependencyObject element)
=> (bool)element.GetValue(ShowCloseButtonProperty);
}
}
@@ -0,0 +1,41 @@
namespace WxOrder.Framework.Commons.Dialogs
{
/// <summary>
/// The result of the dialog.
/// </summary>
public enum ButtonResult
{
/// <summary>
/// Abort.
/// </summary>
Abort = 3,
/// <summary>
/// Cancel.
/// </summary>
Cancel = 2,
/// <summary>
/// Ignore.
/// </summary>
Ignore = 5,
/// <summary>
/// No.
/// </summary>
No = 7,
/// <summary>
/// No result returned.
/// </summary>
None = 0,
/// <summary>
/// OK.
/// </summary>
OK = 1,
/// <summary>
/// Retry.
/// </summary>
Retry = 4,
/// <summary>
/// Yes.
/// </summary>
Yes = 6
}
}
@@ -0,0 +1,82 @@
#if HAS_UWP
using Windows.UI.Xaml;
#elif HAS_WINUI
using Microsoft.UI.Xaml;
#else
using System.Windows;
#endif
namespace WxOrder.Framework.Commons.Dialogs
{
/// <summary>
/// This class contains <see cref="IDialogWindow"/> attached properties.
/// </summary>
public class Dialog
{
/// <summary>
/// Identifies the WindowStyle attached property.
/// </summary>
/// <remarks>
/// This attached property is used to specify the style of a <see cref="IDialogWindow"/>.
/// </remarks>
public static readonly DependencyProperty WindowStyleProperty =
DependencyProperty.RegisterAttached("WindowStyle", typeof(Style), typeof(Dialog), new PropertyMetadata(null));
/// <summary>
/// Gets the value for the <see cref="WindowStyleProperty"/> attached property.
/// </summary>
/// <param name="obj">The target element.</param>
/// <returns>The <see cref="WindowStyleProperty"/> attached to the <paramref name="obj"/> element.</returns>
public static Style GetWindowStyle(DependencyObject obj)
{
return (Style)obj.GetValue(WindowStyleProperty);
}
/// <summary>
/// Sets the <see cref="WindowStyleProperty"/> attached property.
/// </summary>
/// <param name="obj">The target element.</param>
/// <param name="value">The Style to attach.</param>
public static void SetWindowStyle(DependencyObject obj, Style value)
{
obj.SetValue(WindowStyleProperty, value);
}
#if !HAS_UWP && !HAS_WINUI
/// <summary>
/// Identifies the WindowStartupLocation attached property.
/// </summary>
/// <remarks>
/// This attached property is used to specify the startup location of a <see cref="IDialogWindow"/>.
/// </remarks>
public static readonly DependencyProperty WindowStartupLocationProperty =
DependencyProperty.RegisterAttached("WindowStartupLocation", typeof(WindowStartupLocation), typeof(Dialog), new UIPropertyMetadata(OnWindowStartupLocationChanged));
/// <summary>
/// Gets the value for the <see cref="WindowStartupLocationProperty"/> attached property.
/// </summary>
/// <param name="obj">The target element.</param>
/// <returns>The <see cref="WindowStartupLocationProperty"/> attached to the <paramref name="obj"/> element.</returns>
public static WindowStartupLocation GetWindowStartupLocation(DependencyObject obj)
{
return (WindowStartupLocation)obj.GetValue(WindowStartupLocationProperty);
}
/// <summary>
/// Sets the <see cref="WindowStartupLocationProperty"/> attached property.
/// </summary>
/// <param name="obj">The target element.</param>
/// <param name="value">The WindowStartupLocation to attach.</param>
public static void SetWindowStartupLocation(DependencyObject obj, WindowStartupLocation value)
{
obj.SetValue(WindowStartupLocationProperty, value);
}
private static void OnWindowStartupLocationChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (sender is Window window)
window.WindowStartupLocation = (WindowStartupLocation)e.NewValue;
}
#endif
}
}
@@ -0,0 +1,22 @@
namespace WxOrder.Framework.Commons.Dialogs
{
/// <summary>
/// Represents Dialog parameters.
/// </summary>
/// <remarks>
/// This class can be used to to pass object parameters during the showing and closing of Dialogs.
/// </remarks>
public class DialogParameters : ParametersBase, IDialogParameters
{
/// <summary>
/// Initializes a new instance of the <see cref="DialogParameters"/> class.
/// </summary>
public DialogParameters() : base() { }
/// <summary>
/// Constructs a list of parameters.
/// </summary>
/// <param name="query">Query string to be parsed.</param>
public DialogParameters(string query) : base(query) { }
}
}
@@ -0,0 +1,44 @@
namespace WxOrder.Framework.Commons.Dialogs
{
/// <summary>
/// An <see cref="IDialogResult"/> that contains <see cref="IDialogParameters"/> from the dialog
/// and the <see cref="ButtonResult"/> of the dialog.
/// </summary>
public class DialogResult : IDialogResult
{
/// <summary>
/// The parameters from the dialog.
/// </summary>
public IDialogParameters Parameters { get; private set; } = new DialogParameters();
/// <summary>
/// The result of the dialog.
/// </summary>
public ButtonResult Result { get; private set; } = ButtonResult.None;
/// <summary>
/// Initializes a new instance of the <see cref="DialogResult"/> class.
/// </summary>
public DialogResult() { }
/// <summary>
/// Initializes a new instance of the <see cref="DialogResult"/> class.
/// </summary>
/// <param name="result">The result of the dialog.</param>
public DialogResult(ButtonResult result)
{
Result = result;
}
/// <summary>
/// Initializes a new instance of the <see cref="DialogResult"/> class.
/// </summary>
/// <param name="result">The result of the dialog.</param>
/// <param name="parameters">The parameters from the dialog.</param>
public DialogResult(ButtonResult result, IDialogParameters parameters)
{
Result = result;
Parameters = parameters;
}
}
}
@@ -0,0 +1,168 @@
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
namespace WxOrder.Framework.Commons.Dialogs
{
/// <summary>
/// 静态弹窗服务:不依赖容器,直接传入 View 实例弹出。
/// ViewModel 需实现 IDialogAware。
/// </summary>
public static class DialogService
{
// ========== 对外接口 ==========
/// <summary>非模态弹出</summary>
public static void Show(FrameworkElement view,
IDialogParameters parameters = null,
Action<IDialogResult> callback = null,
IDialogWindow window = null)
{
ShowInternal(view, parameters, callback, false, window);
}
/// <summary>模态弹出</summary>
public static void ShowDialog(FrameworkElement view,
IDialogParameters parameters = null,
Action<IDialogResult> callback = null,
IDialogWindow window = null)
{
ShowInternal(view, parameters, callback, true, window);
}
// ========== 内部实现 ==========
private static void ShowInternal(FrameworkElement view,
IDialogParameters parameters,
Action<IDialogResult> callback,
bool isModal,
IDialogWindow window)
{
if (view == null) throw new ArgumentNullException(nameof(view));
if (parameters == null) parameters = new DialogParameters();
// 1. 创建(或使用传入的)DialogWindow
var dialogWindow = window ?? new DialogWindow();
// 2. 绑定事件(关闭、回调等)
ConfigureDialogWindowEvents(dialogWindow, callback);
// 3. 配置内容(View + ViewModel)
ConfigureDialogWindowContent(view, dialogWindow, parameters);
// 4. 弹出
ShowDialogWindow(dialogWindow, isModal);
}
private static void ShowDialogWindow(IDialogWindow dialogWindow, bool isModal)
{
if (isModal)
dialogWindow.ShowDialog();
else
dialogWindow.Show();
}
/// <summary>
/// 把 View 挂到 DialogWindow 上,并触发 OnDialogOpened。
/// </summary>
private static void ConfigureDialogWindowContent(FrameworkElement dialogContent,
IDialogWindow window,
IDialogParameters parameters)
{
// 不再自动绑 ViewModel,DataContext 由 View 自己负责
if (!(dialogContent.DataContext is IDialogAware viewModel))
throw new NullReferenceException("A dialog's ViewModel must implement the IDialogAware interface");
ConfigureDialogWindowProperties(window, dialogContent, viewModel);
// 直接触发 OnDialogOpened(替代 MvvmHelpers.ViewAndViewModelAction)
viewModel.OnDialogOpened(parameters);
}
/// <summary>
/// 绑定 DialogWindow 的生命周期事件。
/// </summary>
private static void ConfigureDialogWindowEvents(IDialogWindow dialogWindow, Action<IDialogResult> callback)
{
Action<IDialogResult> requestCloseHandler = null;
requestCloseHandler = (o) =>
{
dialogWindow.Result = o;
dialogWindow.Close();
};
RoutedEventHandler loadedHandler = null;
loadedHandler = (o, e) =>
{
dialogWindow.Loaded -= loadedHandler;
GetDialogViewModel(dialogWindow).RequestClose += requestCloseHandler;
};
dialogWindow.Loaded += loadedHandler;
CancelEventHandler closingHandler = null;
closingHandler = (o, e) =>
{
if (!GetDialogViewModel(dialogWindow).CanCloseDialog())
e.Cancel = true;
};
dialogWindow.Closing += closingHandler;
EventHandler closedHandler = null;
closedHandler = (o, e) =>
{
dialogWindow.Closed -= closedHandler;
dialogWindow.Closing -= closingHandler;
GetDialogViewModel(dialogWindow).RequestClose -= requestCloseHandler;
GetDialogViewModel(dialogWindow).OnDialogClosed();
if (dialogWindow.Result == null)
dialogWindow.Result = new DialogResult();
callback?.Invoke(dialogWindow.Result);
dialogWindow.DataContext = null;
dialogWindow.Content = null;
};
dialogWindow.Closed += closedHandler;
}
/// <summary>
/// 设置 DialogWindow 的 Style / Content / DataContext / Owner。
/// </summary>
private static void ConfigureDialogWindowProperties(IDialogWindow window,
FrameworkElement dialogContent,
IDialogAware viewModel)
{
var windowStyle = Dialog.GetWindowStyle(dialogContent);
if (windowStyle != null)
window.Style = windowStyle;
window.Content = dialogContent;
window.DataContext = viewModel; // 宿主窗口和对话框共享同一个 DataContext
if (window.Owner == null)
window.Owner = Application.Current?.Windows
.OfType<Window>()
.FirstOrDefault(x => x.IsActive);
}
/// <summary>
/// 从 window.Content 或 window.DataContext 里拿 IDialogAware。
/// 替代 Prism 的 dialogWindow.GetDialogViewModel() 扩展方法。
/// </summary>
private static IDialogAware GetDialogViewModel(IDialogWindow window)
{
if (window.Content is FrameworkElement fe)
{
if (fe is IDialogAware aware) return aware;
if (fe.DataContext is IDialogAware vm) return vm;
}
if (window.DataContext is IDialogAware wvm) return wvm;
throw new NullReferenceException("A dialog's ViewModel must implement the IDialogAware interface");
}
}
}
@@ -0,0 +1,37 @@
using System;
namespace WxOrder.Framework.Commons.Dialogs
{
/// <summary>
/// Interface that provides dialog functions and events to ViewModels.
/// </summary>
public interface IDialogAware
{
/// <summary>
/// Determines if the dialog can be closed.
/// </summary>
/// <returns>If <c>true</c> the dialog can be closed. If <c>false</c> the dialog will not close.</returns>
bool CanCloseDialog();
/// <summary>
/// Called when the dialog is closed.
/// </summary>
void OnDialogClosed();
/// <summary>
/// Called when the dialog is opened.
/// </summary>
/// <param name="parameters">The parameters passed to the dialog.</param>
void OnDialogOpened(IDialogParameters parameters);
/// <summary>
/// The title of the dialog that will show in the window title bar.
/// </summary>
string Title { get; }
/// <summary>
/// Instructs the <see cref="IDialogWindow"/> to close the dialog.
/// </summary>
event Action<IDialogResult> RequestClose;
}
}
@@ -0,0 +1,63 @@
using System.Collections.Generic;
namespace WxOrder.Framework.Commons.Dialogs
{
/// <summary>
/// Represents Dialog parameters.
/// </summary>
/// <remarks>
/// A class that implements this interface can be used to pass
/// object parameters during the showing and closing of Dialogs.
/// </remarks>
public interface IDialogParameters
{
/// <summary>
/// Adds the key and value to the collection.
/// </summary>
/// <param name="key">The key to reference this parameter value in the collection.</param>
/// <param name="value">The parameter value to store.</param>
void Add(string key, object value);
/// <summary>
/// Checks the collection for the presence of a key.
/// </summary>
/// <param name="key">The key to check.</param>
/// <returns><c>true</c> if key exists; <c>false</c> otherwise.</returns>
bool ContainsKey(string key);
/// <summary>
/// The number of parameters in the collection.
/// </summary>
int Count { get; }
/// <summary>
/// The keys in the collection.
/// </summary>
IEnumerable<string> Keys { get; }
/// <summary>
/// Gets the parameter value referenced by a key.
/// </summary>
/// <typeparam name="T">The type of object to be returned.</typeparam>
/// <param name="key">The key of the parameter value to be returned.</param>
/// <returns>The matching parameter of type <typeparamref name="T"/>.</returns>
T GetValue<T>(string key);
/// <summary>
/// Gets all parameter values referenced by a key.
/// </summary>
/// <typeparam name="T">The type of object to be returned.</typeparam>
/// <param name="key">The key of the parameter values to be returned.</param>
///<returns>All matching parameter values of type <typeparamref name="T"/>.</returns>
IEnumerable<T> GetValues<T>(string key);
/// <summary>
/// Gets the parameter value if the referenced key exists.
/// </summary>
/// <typeparam name="T">The type of object to be returned.</typeparam>
/// <param name="key">The key of the parameter value to be returned.</param>
/// <param name="value">The matching parameter of type <typeparamref name="T"/> if the key exists.</param>
/// <returns><c>true</c> if the parameter exists; <c>false</c> otherwise.</returns>
bool TryGetValue<T>(string key, out T value);
}
}
@@ -0,0 +1,19 @@
namespace WxOrder.Framework.Commons.Dialogs
{
/// <summary>
/// Contains <see cref="IDialogParameters"/> from the dialog
/// and the <see cref="ButtonResult"/> of the dialog.
/// </summary>
public interface IDialogResult
{
/// <summary>
/// The parameters from the dialog.
/// </summary>
IDialogParameters Parameters { get; }
/// <summary>
/// The result of the dialog.
/// </summary>
ButtonResult Result { get; }
}
}
@@ -0,0 +1,71 @@
using System;
using System.ComponentModel;
using System.Windows;
namespace WxOrder.Framework.Commons.Dialogs
{
/// <summary>
/// Interface for a dialog hosting window.
/// </summary>
public interface IDialogWindow
{
/// <summary>
/// Dialog content.
/// </summary>
object Content { get; set; }
/// <summary>
/// Close the window.
/// </summary>
void Close();
/// <summary>
/// The window's owner.
/// </summary>
Window Owner { get; set; }
/// <summary>
/// Show a non-modal dialog.
/// </summary>
void Show();
/// <summary>
/// Show a modal dialog.
/// </summary>
/// <returns></returns>
bool? ShowDialog();
/// <summary>
/// The data context of the window.
/// </summary>
/// <remarks>
/// The data context must implement <see cref="IDialogAware"/>.
/// </remarks>
object DataContext { get; set; }
/// <summary>
/// Called when the window is loaded.
/// </summary>
event RoutedEventHandler Loaded;
/// <summary>
/// Called when the window is closed.
/// </summary>
event EventHandler Closed;
/// <summary>
/// Called when the window is closing.
/// </summary>
event CancelEventHandler Closing;
/// <summary>
/// The result of the dialog.
/// </summary>
IDialogResult Result { get; set; }
/// <summary>
/// The window style.
/// </summary>
Style Style { get; set; }
}
}
@@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WxOrder.Framework.Commons.Dialogs
{
/// <summary>
/// Defines a contract for specifying values associated with a unique key.
/// </summary>
public interface IParameters : IEnumerable<KeyValuePair<string, object>>
{
/// <summary>
/// Adds the specified key and value to the parameter collection.
/// </summary>
/// <param name="key">The key of the parameter to add.</param>
/// <param name="value">The value of the parameter to add.</param>
void Add(string key, object value);
/// <summary>
/// Determines whether the <see cref="IParameters"/> contains the specified <paramref name="key"/>.
/// </summary>
/// <param name="key">The key to search the parameters for existence.</param>
/// <returns>true if the <see cref="IParameters"/> contains a parameter with the specified key; otherwise, false.</returns>
bool ContainsKey(string key);
/// <summary>
/// Gets the number of parameters contained in the <see cref="IParameters"/>.
/// </summary>
int Count { get; }
/// <summary>
/// Gets a collection containing the keys in the <see cref="IParameters"/>.
/// </summary>
IEnumerable<string> Keys { get; }
/// <summary>
/// Gets the parameter associated with the specified <paramref name="key"/>.
/// </summary>
/// <typeparam name="T">The type of the parameter to get.</typeparam>
/// <param name="key">The key of the parameter to find.</param>
/// <returns>A matching value of <typeparamref name="T"/> if it exists.</returns>
T GetValue<T>(string key);
/// <summary>
/// Gets the parameter associated with the specified <paramref name="key"/>.
/// </summary>
/// <typeparam name="T">The type of the parameter to get.</typeparam>
/// <param name="key">The key of the parameter to find.</param>
/// <returns>An <see cref="IEnumerable{T}"/> of all the values referenced by key.</returns>
IEnumerable<T> GetValues<T>(string key);
/// <summary>
/// Gets the parameter associated with the specified <paramref name="key"/>.
/// </summary>
/// <typeparam name="T">The type of the parameter to get.</typeparam>
/// <param name="key">The key of the parameter to get.</param>
/// <param name="value">
/// When this method returns, contains the parameter associated with the specified key,
/// if the key is found; otherwise, the default value for the type of the value parameter.
/// </param>
/// <returns>true if the <see cref="IParameters"/> contains a parameter with the specified key; otherwise, false.</returns>
bool TryGetValue<T>(string key, out T value);
/// <summary>
/// Gets the parameter associated with the specified key (legacy).
/// </summary>
/// <param name="key">The key of the parameter to get.</param>
/// <returns>A matching value if it exists.</returns>
object this[string key] { get; }
}
}
@@ -0,0 +1,198 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace WxOrder.Framework.Commons.Dialogs
{
/// <summary>
/// This is a generic parameters base class used for Dialog Parameters and Navigation Parameters.
/// </summary>
public abstract class ParametersBase : IParameters, IEnumerable<KeyValuePair<string, object>>
{
private readonly List<KeyValuePair<string, object>> _entries = new List<KeyValuePair<string, object>>();
/// <summary>
/// Default constructor.
/// </summary>
protected ParametersBase()
{
}
/// <summary>
/// Constructs a list of parameters.
/// </summary>
/// <param name="query">Query string to be parsed.</param>
protected ParametersBase(string query)
{
if (!string.IsNullOrWhiteSpace(query))
{
int num = query.Length;
for (int i = ((query.Length > 0) && (query[0] == '?')) ? 1 : 0; i < num; i++)
{
int startIndex = i;
int num4 = -1;
while (i < num)
{
char ch = query[i];
if (ch == '=')
{
if (num4 < 0)
{
num4 = i;
}
}
else if (ch == '&')
{
break;
}
i++;
}
string key = null;
string value;
if (num4 >= 0)
{
key = query.Substring(startIndex, num4 - startIndex);
value = query.Substring(num4 + 1, (i - num4) - 1);
}
else
{
value = query.Substring(startIndex, i - startIndex);
}
if (key != null)
Add(Uri.UnescapeDataString(key), Uri.UnescapeDataString(value));
}
}
}
/// <summary>
/// Searches Parameter collection and returns value if Collection contains key.
/// Otherwise returns null.
/// </summary>
/// <param name="key">The key for the value to be returned.</param>
/// <returns>The value of the parameter referenced by the key; otherwise <c>null</c>.</returns>
public object this[string key]
{
get
{
foreach (var entry in _entries)
{
if (string.Compare(entry.Key, key, StringComparison.Ordinal) == 0)
{
return entry.Value;
}
}
return null;
}
}
/// <summary>
/// The count, or number, of parameters in collection.
/// </summary>
public int Count => _entries.Count;
/// <summary>
/// Returns an IEnumerable of the Keys in the collection.
/// </summary>
public IEnumerable<string> Keys =>
_entries.Select(x => x.Key);
/// <summary>
/// Adds the key and value to the parameters collection.
/// </summary>
/// <param name="key">The key to reference this value in the parameters collection.</param>
/// <param name="value">The value of the parameter to store.</param>
public void Add(string key, object value) =>
_entries.Add(new KeyValuePair<string, object>(key, value));
/// <summary>
/// Checks collection for presence of key.
/// </summary>
/// <param name="key">The key to check in the collection.</param>
/// <returns><c>true</c> if key exists; else returns <c>false</c>.</returns>
public bool ContainsKey(string key) =>
_entries.ContainsKey(key);
/// <summary>
/// Gets an enumerator for the KeyValuePairs in parameter collection.
/// </summary>
/// <returns>Enumerator.</returns>
public IEnumerator<KeyValuePair<string, object>> GetEnumerator() =>
_entries.GetEnumerator();
/// <summary>
/// Returns the value of the member referenced by key.
/// </summary>
/// <typeparam name="T">The type of object to be returned.</typeparam>
/// <param name="key">The key for the value to be returned.</param>
/// <returns>Returns a matching parameter of <typeparamref name="T"/> if one exists in the Collection.</returns>
public T GetValue<T>(string key) =>
_entries.GetValue<T>(key);
/// <summary>
/// Returns an IEnumerable of all parameters.
/// </summary>
/// <typeparam name="T">The type for the values to be returned.</typeparam>
/// <param name="key">The key for the values to be returned.</param>
///<returns>Returns a IEnumerable of all the instances of type <typeparamref name="T"/>.</returns>
public IEnumerable<T> GetValues<T>(string key) =>
_entries.GetValues<T>(key);
/// <summary>
/// Checks to see if the parameter collection contains the value.
/// </summary>
/// <typeparam name="T">The type for the values to be returned.</typeparam>
/// <param name="key">The key for the value to be returned.</param>
/// <param name="value">Value of the returned parameter if it exists.</param>
public bool TryGetValue<T>(string key, out T value) =>
_entries.TryGetValue(key, out value);
IEnumerator IEnumerable.GetEnumerator() =>
GetEnumerator();
/// <summary>
/// Converts parameter collection to a parameter string.
/// </summary>
/// <returns>A string representation of the parameters.</returns>
public override string ToString()
{
var queryBuilder = new StringBuilder();
if (_entries.Count > 0)
{
queryBuilder.Append('?');
var first = true;
foreach (var kvp in _entries)
{
if (!first)
{
queryBuilder.Append('&');
}
else
{
first = false;
}
queryBuilder.Append(Uri.EscapeDataString(kvp.Key));
queryBuilder.Append('=');
queryBuilder.Append(Uri.EscapeDataString(kvp.Value != null ? kvp.Value.ToString() : ""));
}
}
return queryBuilder.ToString();
}
/// <summary>
/// Adds a collection of parameters to the local parameter list.
/// </summary>
/// <param name="parameters">An IEnumerable of KeyValuePairs to add to the current parameter list.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
public void FromParameters(IEnumerable<KeyValuePair<string, object>> parameters) =>
_entries.AddRange(parameters);
}
}
@@ -0,0 +1,163 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace WxOrder.Framework.Commons.Dialogs
{
/// <summary>
/// Extension methods for Navigation or Dialog parameters
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ParametersExtensions
{
/// <summary>
/// Searches <paramref name="parameters"/> for <paramref name="key"/>
/// </summary>
/// <typeparam name="T">The type of the parameter to return</typeparam>
/// <param name="parameters">A collection of parameters to search</param>
/// <param name="key">The key of the parameter to find</param>
/// <returns>A matching value of <typeparamref name="T"/> if it exists</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public static T GetValue<T>(this IEnumerable<KeyValuePair<string, object>> parameters, string key) =>
(T)GetValue(parameters, key, typeof(T));
/// <summary>
/// Searches <paramref name="parameters"/> for value referenced by <paramref name="key"/>
/// </summary>
/// <param name="parameters">A collection of parameters to search</param>
/// <param name="key">The key of the parameter to find</param>
/// <param name="type">The type of the parameter to return</param>
/// <returns>A matching value of <paramref name="type"/> if it exists</returns>
/// <exception cref="InvalidCastException">Unable to convert the value of Type</exception>
[EditorBrowsable(EditorBrowsableState.Never)]
public static object GetValue(this IEnumerable<KeyValuePair<string, object>> parameters, string key, Type type)
{
foreach (var kvp in parameters)
{
if (string.Compare(kvp.Key, key, StringComparison.Ordinal) == 0)
{
if (TryGetValueInternal(kvp, type, out var value))
return value;
throw new InvalidCastException($"Unable to convert the value of Type '{kvp.Value.GetType().FullName}' to '{type.FullName}' for the key '{key}' ");
}
}
return GetDefault(type);
}
/// <summary>
/// Searches <paramref name="parameters"/> for value referenced by <paramref name="key"/>
/// </summary>
/// <typeparam name="T">The type of the parameter to return</typeparam>
/// <param name="parameters">A collection of parameters to search</param>
/// <param name="key">The key of the parameter to find</param>
/// <param name="value">The value of parameter to return</param>
/// <returns>Success if value is found; otherwise returns <c>false</c></returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public static bool TryGetValue<T>(this IEnumerable<KeyValuePair<string, object>> parameters, string key, out T value)
{
var type = typeof(T);
foreach (var kvp in parameters)
{
if (string.Compare(kvp.Key, key, StringComparison.Ordinal) == 0)
{
var success = TryGetValueInternal(kvp, typeof(T), out object valueAsObject);
value = (T)valueAsObject;
return success;
}
}
value = default;
return false;
}
/// <summary>
/// Searches <paramref name="parameters"/> for value referenced by <paramref name="key"/>
/// </summary>
/// <typeparam name="T">The type of the parameter to return</typeparam>
/// <param name="parameters">A collection of parameters to search</param>
/// <param name="key">The key of the parameter to find</param>
/// <returns>An IEnumerable{T} of all the values referenced by key</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public static IEnumerable<T> GetValues<T>(this IEnumerable<KeyValuePair<string, object>> parameters, string key)
{
List<T> values = new List<T>();
var type = typeof(T);
foreach (var kvp in parameters)
{
if (string.Compare(kvp.Key, key, StringComparison.Ordinal) == 0)
{
TryGetValueInternal(kvp, type, out var value);
values.Add((T)value);
}
}
return values.AsEnumerable();
}
private static bool TryGetValueInternal(KeyValuePair<string, object> kvp, Type type, out object value)
{
value = GetDefault(type);
var success = false;
if (kvp.Value == null)
{
success = true;
}
else if (kvp.Value.GetType() == type)
{
success = true;
value = kvp.Value;
}
else if (type.IsAssignableFrom(kvp.Value.GetType()))
{
success = true;
value = kvp.Value;
}
else if (type.IsEnum)
{
var valueAsString = kvp.Value.ToString();
if (Enum.IsDefined(type, valueAsString))
{
success = true;
value = Enum.Parse(type, valueAsString);
}
else if (int.TryParse(valueAsString, out var numericValue))
{
success = true;
value = Enum.ToObject(type, numericValue);
}
}
if (!success && type.GetInterface("System.IConvertible") != null)
{
success = true;
value = Convert.ChangeType(kvp.Value, type);
}
return success;
}
/// <summary>
/// Checks to see if key exists in parameter collection
/// </summary>
/// <param name="parameters">IEnumerable to search</param>
/// <param name="key">The key to search the <paramref name="parameters"/> for existence</param>
/// <returns><c>true</c> if key exists; <c>false</c> otherwise</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public static bool ContainsKey(this IEnumerable<KeyValuePair<string, object>> parameters, string key) =>
parameters.Any(x => string.Compare(x.Key, key, StringComparison.Ordinal) == 0);
private static object GetDefault(Type type)
{
if (type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
}
}
@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WxOrder.Framework.Commons;
public class EnvironmentHelper
{
private static string? _currentEnvironment;
// 获取当前环境
public static string CurrentEnvironment
{
get
{
if (_currentEnvironment == null)
{
_currentEnvironment = DetermineEnvironment();
}
return _currentEnvironment;
}
}
public static bool IsTest => CurrentEnvironment.Equals("Test", StringComparison.OrdinalIgnoreCase);
public static bool IsDevelopment => CurrentEnvironment.Equals("Development", StringComparison.OrdinalIgnoreCase);
public static bool IsProduction => CurrentEnvironment.Equals("Production", StringComparison.OrdinalIgnoreCase);
private static string DetermineEnvironment()
{
#if RELEASE
// Release 构建:只允许生产环境,不允许其他环境
return "Production";
#else
// 1. 检查环境变量
var envVar = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ??
Environment.GetEnvironmentVariable("ENVIRONMENT");
if (!string.IsNullOrEmpty(envVar))
{
return envVar;
}
// 检查当前机器名
string machineName = Environment.MachineName.ToLower();
if (machineName.Contains("dev") ||
machineName.Contains("test"))
{
return machineName.Contains("TEST") ? "Test" : "Development";
}
// 4. 默认返回 Production
return "Production";
#endif
}
// 获取环境描述
public static string EnvironmentDescription
{
get
{
if (IsTest) return "测试环境";
if (IsDevelopment) return "开发环境";
if (IsProduction) return "生产环境";
return $"未知环境 ({CurrentEnvironment})";
}
}
}
@@ -0,0 +1,28 @@
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
namespace WxOrder.Framework.Commons
{
/// <summary>
/// Provides an abstraction layer for custom controls which want to make use of Async Commands
/// </summary>
public interface IAsyncCommand : ICommand
{
/// <summary>
/// Executes the Command with a specified parameter and the Default <see cref="CancellationToken"/>.
/// </summary>
/// <param name="parameter">The Command Parameter</param>
/// <returns>An Asynchronous Task</returns>
Task ExecuteAsync(object parameter);
/// <summary>
/// Executes the Command with a specified parameter and using a <see cref="CancellationToken"/>
/// </summary>
/// <param name="parameter">The Command Parameter</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>An Asynchronous Task</returns>
Task ExecuteAsync(object parameter, CancellationToken cancellationToken);
}
}
@@ -0,0 +1,65 @@
<Window
x:Class="WxOrder.Framework.Commons.InputDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WxOrder.Framework.Commons"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="输入"
Width="360"
ContentRendered="Window_ContentRendered"
ResizeMode="NoResize"
ShowInTaskbar="False"
SizeToContent="Height"
WindowStartupLocation="CenterOwner"
mc:Ignorable="d">
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock
x:Name="PromptText"
Grid.Row="0"
Margin="0,0,0,8"
TextWrapping="Wrap" />
<TextBox
x:Name="InputBox"
Grid.Row="1"
Height="26"
VerticalContentAlignment="Center"
PreviewTextInput="InputBox_PreviewTextInput" />
<TextBlock
x:Name="ErrorText"
Grid.Row="2"
Margin="0,6,0,0"
Foreground="Red"
TextWrapping="Wrap"
Visibility="Collapsed" />
<StackPanel
Grid.Row="3"
Margin="0,16,0,0"
HorizontalAlignment="Right"
Orientation="Horizontal">
<Button
Width="80"
Height="28"
Click="Ok_Click"
Content="确定"
IsDefault="True" />
<Button
Width="80"
Height="28"
Margin="8,0,0,0"
Content="取消"
IsCancel="True" />
</StackPanel>
</Grid>
</Window>
@@ -0,0 +1,163 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WxOrder.Framework.Commons;
public enum InputType
{
Text, // 任意文本
Integer, // 整数
Decimal // 小数
}
/// <summary>
/// InputDialog.xaml 的交互逻辑
/// </summary>
public partial class InputDialog : Window
{
private readonly InputType _type;
private readonly bool _allowEmpty;
// 输入过程中允许的"部分输入"格式(如 "-"、"1." 也允许)
private static readonly Regex IntPartial = new(@"^-?\d*$");
private static readonly Regex DecPartial = new(@"^-?\d*\.?\d*$");
/// <summary>用户输入的原始文本</summary>
public string ResultText { get; private set; } = "";
private InputDialog(Window? owner, string title, string prompt,
string defaultValue, InputType type, bool allowEmpty)
{
InitializeComponent();
Owner = owner ?? Application.Current.Windows
.OfType<Window>()
.FirstOrDefault(w => w.IsActive) ?? Application.Current.MainWindow;
if (Owner == null) WindowStartupLocation = WindowStartupLocation.CenterScreen;
Title = title;
PromptText.Text = prompt;
InputBox.Text = defaultValue;
_type = type;
_allowEmpty = allowEmpty;
// 粘贴时同样校验
DataObject.AddPastingHandler(InputBox, (s, e) =>
{
if (_type == InputType.Text) return;
if (e.DataObject.GetData(DataFormats.Text) is not string pasted ||
!IsPartialValid(Preview(pasted)))
e.CancelCommand();
});
}
private void Window_ContentRendered(object? sender, EventArgs e)
{
InputBox.Focus();
InputBox.SelectAll();
}
// 按键输入时实时限制字符
private void InputBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
if (_type == InputType.Text) return;
e.Handled = !IsPartialValid(Preview(e.Text));
}
// 计算输入/粘贴后的文本
private string Preview(string incoming)
{
var t = InputBox.Text;
return t.Remove(InputBox.SelectionStart, InputBox.SelectionLength)
.Insert(InputBox.SelectionStart, incoming);
}
private bool IsPartialValid(string text) => _type switch
{
InputType.Integer => IntPartial.IsMatch(text),
InputType.Decimal => DecPartial.IsMatch(text),
_ => true
};
private void Ok_Click(object sender, RoutedEventArgs e)
{
var text = InputBox.Text.Trim();
if (text.Length == 0 && !_allowEmpty)
{
ShowError("内容不能为空");
return;
}
if (text.Length > 0)
{
if (_type == InputType.Integer && !int.TryParse(text, NumberStyles.AllowLeadingSign,
CultureInfo.InvariantCulture, out _))
{
ShowError("请输入有效的整数");
return;
}
if (_type == InputType.Decimal && !double.TryParse(text, NumberStyles.Float,
CultureInfo.InvariantCulture, out _))
{
ShowError("请输入有效的数字");
return;
}
}
ResultText = text;
DialogResult = true;
}
private void ShowError(string msg)
{
ErrorText.Text = msg;
ErrorText.Visibility = Visibility.Visible;
InputBox.Focus();
InputBox.SelectAll();
}
// ================= 静态帮助方法 =================
/// <summary>输入文本。取消返回 null。</summary>
public static string? ShowText(string prompt, string title = "输入",
string defaultValue = "", bool allowEmpty = false, Window? owner = null)
{
var dlg = new InputDialog(owner, title, prompt, defaultValue, InputType.Text, allowEmpty);
return dlg.ShowDialog() == true ? dlg.ResultText : null;
}
/// <summary>输入整数。取消返回 null。</summary>
public static int? ShowInt(string prompt, string title = "输入",
int? defaultValue = null, Window? owner = null)
{
var dlg = new InputDialog(owner, title, prompt,
defaultValue?.ToString(CultureInfo.InvariantCulture) ?? "", InputType.Integer, false);
return dlg.ShowDialog() == true
? int.Parse(dlg.ResultText, CultureInfo.InvariantCulture)
: null;
}
/// <summary>输入小数。取消返回 null。</summary>
public static double? ShowDouble(string prompt, string title = "输入",
double? defaultValue = null, Window? owner = null)
{
var dlg = new InputDialog(owner, title, prompt,
defaultValue?.ToString(CultureInfo.InvariantCulture) ?? "", InputType.Decimal, false);
return dlg.ShowDialog() == true
? double.Parse(dlg.ResultText, CultureInfo.InvariantCulture)
: null;
}
}
@@ -0,0 +1,109 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace WxOrder.Framework.Commons
{
/// <summary>
/// 让页面级 ScrollViewer 在鼠标悬停在子控件(如 DataGrid、图表等)上时也能随鼠标滚轮滚动。
/// 用法:在 ScrollViewer 上设置 common:ScrollViewerBehavior.FixMouseWheel="True"。
/// </summary>
public static class ScrollViewerBehavior
{
public static readonly DependencyProperty FixMouseWheelProperty =
DependencyProperty.RegisterAttached(
"FixMouseWheel",
typeof(bool),
typeof(ScrollViewerBehavior),
new PropertyMetadata(false, OnFixMouseWheelChanged));
public static bool GetFixMouseWheel(DependencyObject obj)
=> (bool)obj.GetValue(FixMouseWheelProperty);
public static void SetFixMouseWheel(DependencyObject obj, bool value)
=> obj.SetValue(FixMouseWheelProperty, value);
private static void OnFixMouseWheelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is ScrollViewer scrollViewer))
{
return;
}
if ((bool)e.NewValue)
{
scrollViewer.PreviewMouseWheel += OnPreviewMouseWheel;
}
else
{
scrollViewer.PreviewMouseWheel -= OnPreviewMouseWheel;
}
}
private static void OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
if (e.Handled || !(sender is ScrollViewer scrollViewer) || scrollViewer.ScrollableHeight <= 0)
{
return;
}
if (!(e.OriginalSource is DependencyObject original))
{
return;
}
// 从鼠标所在控件向上查找,确认它属于当前 ScrollViewer
var current = original;
var inside = false;
while (current != null)
{
if (ReferenceEquals(current, scrollViewer))
{
inside = true;
break;
}
// 若鼠标位于一个能自行纵向滚动的内部 ScrollViewer 上(例如下拉列表、
// 启用了滚动的表格),则交给内部处理,避免抢走它的滚动。
if (current is ScrollViewer inner &&
inner.ComputedVerticalScrollBarVisibility == Visibility.Visible &&
inner.ScrollableHeight > 0)
{
return;
}
current = VisualTreeHelper.GetParent(current);
}
if (!inside)
{
return;
}
// 按系统默认的滚轮行数滚动当前页面
var lines = (int)(e.Delta / Mouse.MouseWheelDeltaForOneLine * SystemParameters.WheelScrollLines);
if (lines == 0)
{
lines = e.Delta > 0 ? 1 : -1;
}
if (lines < 0)
{
for (var i = 0; i < -lines; i++)
{
scrollViewer.LineDown();
}
}
else
{
for (var i = 0; i < lines; i++)
{
scrollViewer.LineUp();
}
}
e.Handled = true;
}
}
}
@@ -0,0 +1,15 @@
namespace WxOrder.Framework.Commons.pinyin.Data
{
public static class PinyinCode1
{
public static byte[] PINYIN_CODE_PADDING = new byte[]
{
177,79,200,37,169,41,96,13,134,58,2,134,67,33,184,128,16,79,211,92,75,40,54,206,19,34,241,102,32,39,53,25,201,37,194,233,28,47,168,151,133,170,159,151,26,160,0,204,151,176,3,116,69,64,36,15,103,74,178,194,31,81,68,50,154,196,73,21,145,176,40,124,41,118,173,84,223,152,167,37,218,134,12,253,48,228,242,232,2,220,89,192,136,66,156,160,153,96,12,40,128,151,49,26,223,65,240,131,96,69,20,170,80,34,146,163,28,34,64,80,202,4,65,65,0,0,96,129,24,65,74,66,9,4,192,1,136,5,16,20,71,34,9,17,48,128,40,52,194,242,128,131,128,41,192,62,148,35,141,141,1,9,16,48,24,16,144,45,231,185,29,8,169,105,87,155,161,252,152,154,78,100,248,142,19,89,252,210,2,21,93,3,226,16,23,198,12,80,30,73,1,130,10,209,98,47,153,142,12,136,140,112,112,89,135,173,172,38,10,128,2,201,12,65,67,153,115,4,12,203,129,118,114,248,32,67,169,57,26,21,118,144,159,16,143,38,93,12,166,43,104,84,78,70,32,232,192,8,97,1,22,153,114,24,135,204,72,230,10,92,139,200,168,129,16,69,40,64,210,12,5,57,131,142,77,34,28,209,82,231,236,153,159,155,24,0,59,32,9,72,233,81,34,66,2,24,144,132,169,33,192,176,192,160,2,147,74,74,210,41,4,34,129,130,136,152,65,10,192,88,183,197,86,122,0,112,160,18,228,208,131,56,161,128,240,80,72,56,210,216,51,170,39,204,233,50,16,103,186,32,16,132,168,69,76,40,0,66,86,228,97,177,178,134,243,32,10,126,188,46,1,37,196,205,107,76,10,72,147,253,87,6,0,26,71,65,9,50,210,199,207,2,195,250,217,96,251,0,93,53,160,90,40,16,160,13,76,7,167,129,32,210,17,163,225,99,225,114,67,8,77,69,236,125,133,218,186,167,179,130,42,5,26,35,84,15,22,140,20,159,130,142,157,46,1,67,136,107,106,208,137,176,14,218,82,131,64,225,144,75,25,2,29,8,174,162,42,76,152,226,48,2,100,128,220,164,187,126,9,230,188,77,19,27,130,1,157,102,82,129,212,93,165,121,196,180,192,69,66,136,237,37,37,153,67,150,177,61,184,10,91,0,13,137,0,0,1,53,86,145,18,33,191,99,64,127,5,73,34,114,2,193,251,0,132,219,38,70,69,216,39,32,128,64,64,121,254,64,51,7,203,162,5,162,6,236,49,8,93,97,135,53,245,87,140,14,14,225,144,96,142,81,147,139,28,22,120,195,88,208,2,163,225,22,37,205,97,88,0,136,34,24,121,209,44,0,28,199,152,139,18,36,7,221,96,155,237,106,2,192,50,168,115,66,54,65,192,139,4,68,92,41,57,83,160,6,32,91,0,195,136,246,2,1,65,168,39,4,241,220,144,147,176,24,35,77,66,249,46,193,128,242,17,81,24,0,104,10,32,162,120,98,136,8,75,244,72,194,6,110,36,67,14,182,96,1,25,225,41,145,200,82,68,43,130,72,50,122,249,180,35,16,94,197,136,115,82,181,131,133,46,85,181,46,16,1,41,176,244,132,16,236,36,82,0,129,139,72,226,80,36,72,22,15,132,202,186,32,100,49,52,129,72,129,16,33,20,1,42,98,81,29,227,73,80,209,70,222,47,181,8,136,75,209,33,63,84,167,137,32,250,182,11,233,131,80,165,180,62,236,29,62,31,23,215,65,7,13,34,24,68,194,177,219,131,27,200,112,47,137,21,7,57,24,15,228,6,98,173,182,92,162,66,25,24,85,13,34,117,233,12,98,46,120,6,36,216,111,26,0,226,146,49,3,47,22,171,150,144,36,168,216,71,151,7,190,96,33,28,58,56,164,164,176,77,48,2,0,160,24,149,254,136,67,33,228,24,66,32,104,77,95,77,23,52
};
public static byte[] PINYIN_CODE = new byte[]
{
104,68,147,250,33,86,0,78,127,24,33,86,129,21,111,197,92,40,40,139,255,241,39,39,3,19,103,49,70,49,37,69,3,172,69,110,172,100,19,25,41,138,96,99,253,134,129,134,87,105,43,32,175,143,136,0,78,58,80,136,136,169,139,244,90,104,104,207,0,138,138,75,192,104,0,133,84,124,121,82,166,134,246,236,254,121,104,37,37,104,106,0,199,138,250,103,85,88,92,69,0,0,41,0,39,129,209,130,0,39,0,0,188,181,0,17,85,100,90,30,206,93,0,0,0,0,252,133,107,93,181,175,104,141,166,0,111,132,39,39,80,41,111,158,111,114,121,250,84,136,49,54,98,98,99,90,99,250,99,129,70,79,146,57,133,111,104,32,118,205,0,88,136,68,172,118,136,103,0,20,110,90,58,171,76,80,12,12,129,0,79,104,37,12,166,68,120,135,249,40,6,127,135,134,19,13,49,88,24,182,0,25,144,39,57,127,90,87,87,30,119,69,12,252,93,96,63,57,176,104,34,33,22,33,104,205,194,12,130,34,101,252,134,241,78,84,131,130,102,87,25,12,79,86,63,84,134,250,238,111,66,75,81,104,91,146,104,129,2,84,129,90,82,94,135,11,36,90,60,134,110,128,126,111,53,114,24,80,43,35,99,87,33,33,182,25,98,91,80,136,38,96,210,20,102,216,216,90,8,95,176,135,37,4,49,13,49,130,241,104,49,2,132,65,112,188,58,136,21,4,14,34,48,80,63,136,151,110,101,64,126,115,14,75,35,111,104,88,151,101,222,69,216,96,139,109,76,252,0,143,0,238,123,115,165,88,96,101,7,82,201,130,207,19,129,118,128,107,5,66,133,48,104,39,92,37,75,145,133,92,162,104,38,154,106,169,106,39,196,136,95,110,3,180,204,80,182,70,30,38,98,100,135,104,17,131,86,130,116,184,0,133,131,27,254,155,31,222,224,135,84,120,137,37,131,55,40,0,184,139,41,68,37,75,20,208,114,15,73,111,85,51,77,3,95,157,153,84,142,104,90,164,147,254,169,109,127,136,87,24,234,52,90,85,169,197,246,10,111,49,86,91,94,111,64,35,40,0,100,172,169,162,49,131,94,90,115,139,89,234,131,16,64,85,87,99,3,11,111,91,14,38,33,133,19,117,102,53,170,78,162,25,145,96,105,11,65,41,41,194,60,59,141,45,92,240,60,120,104,250,64,93,136,134,95,33,134,84,133,151,140,145,139,252,216,182,143,83,183,50,168,127,70,144,12,84,139,207,23,131,125,103,133,30,1,0,107,37,252,100,227,134,46,130,134,80,111,19,21,64,80,242,100,87,60,83,77,90,35,38,145,63,151,30,68,11,103,125,102,126,3,100,110,131,95,124,31,90,14,133,145,197,129,104,90,98,49,73,27,131,232,70,70,11,115,179,134,80,86,33,158,51,38,52,86,90,112,15,169,17,114,101,187,9,65,60,114,134,85,32,252,141,25,41,24,11,89,109,102,57,56,79,82,19,130,57,116,60,0,18,41,228,117,167,53,109,119,145,240,50,5,43,111,125,147,33,253,253,38,30,112,127,1,100,63,85,179,11,243,135,171,180,189,252,87,3,107,70,139,88,32,254,137,73,150,249,85,165,33,106,173,250,62,32,80,127,83,126,43,67,58,133,138,29,86,87,141,77,133,131,69,175,20,102,87,52,87,132,200,103,135,130,254,241,87,135,2,23,104,142,224,32,104,59,136,96,155,131,41,58,133,30,116,0,18,3,17,58,40,31,163,216,135,252,195,84,214,2,216,33,174,167,184,157,10,72,16,117,133,49,110,114,0,36,169,63,80,178,41,32,9,41,126,169,183,117,228,60,100,167,209,80,84,114,117,112,93,39,128,93,87,106,74,148,74,197,71,33,80,74,80,135,71,49,100,100,39,39,59,252,71,86,191,91,71,7,136,169,157,17,79,212,5,172,111,6,100,177,85,0,163,100,65,105,92,19,250,139,65,144,0,101,131,40,129,104,129,32,137,191,8,212,112,191,94,8,27,137,27,116,103,137,191,135,191,101,95,197,196,15,106,90,145,142,224,104,196,39,105,195,134,149,112,201,152,0,90,90,196,19,70,58,94,87,19,121,39,141,121,157,103,168,235,90,200,70,87,174,86,131,136,41,193,33,250,102,142,50,136,172,1,66,176,70,93,131,106,50,2,169,25,201,142,53,49,76,135,175,175,222,85,72,129,83,83,83,87,139,41,0,87,0,0,90,87,246,87,144,125,144,93,62,246,4,93,155,71,5,41,129,59,112,112,119,60,66,60,12,12,44,86,255,104,129,145,252,54,41,81,129,58,92,122,78,141,169,113,174,177,120,94,44,90,41,4,139,32,200,176,134,235,17,134,134,10,169,32,17,32,136,103,98,60,44,158,153,76,80,133,42,5,30,48,148,134,107,48,107,144,76,129,64,136,179,183,120,112,55,97,148,161,252,30,43,103,131,55,169,64,85,248,32,250,44,144,94,78,20,129,76,1,100,143,131,129,20,100,139,128,38,131,76,73,84,103,90,38,131,96,124,144,44,140,32,72,180,169,89,32,243,152,133,103,254,141,122,124,143,171,139,241,177,107,133,107,131,131,60,128,129,131,104,131,133,32,52,203,169,136,169,99,5,8,100,130,84,188,174,136,150,90,133,70,136,226,134,4,34,104,136,203,169,136,165,165,140,152,101,76,89,204,157,134,174,115,39,148,136,114,20,200,38,164,109,109,197,148,98,140,1,180,21,195,162,166,144,197,70,95,95,145,84,104,98,82,38,165,205,180,243,39,129,0,253,133,5,88,104,254,83,140,69,139,58,90,188,98,98,184,169,35,9,5,10,34,114,138,10,101,84,114,0,0,92,92,10,49,0,93,240,139,61,96,249,3,237,90,100,56,138,2,14,122,11,210,38,84,138,104,115,132,146,132,157,121,86,4,83,107,255,25,157,85,121,111,107,158,126,58,158,171,171,53,72,138,4,85,241,4,104,3,100,15,216,4,39,91,252,217,22,147,38,84,126,8,39,85,78,122,90,78,11,147,143,90,58,188,208,58,129,20,43,21,157,15,21,126,143,180,110,180,85,103,83,90,134,134,80,4,2,133,191,106,80,34,129,6,181,39,140,90,95,135,6,84,129,77,1,85,0,33,112,77,68,169,129,3,169,99,99,100,35,133,124,236,0,148,99,133,27,236,64,169,35,120,68,149,55,85,112,27,112,88,100,169,141,30,65,41,138,0,Line truncated
};
}
}
@@ -0,0 +1,15 @@
namespace WxOrder.Framework.Commons.pinyin.Data
{
public static class PinyinCode2
{
public static byte[] PINYIN_CODE_PADDING = new byte[]
{
128,246,161,5,7,104,160,33,238,10,249,237,47,84,4,100,17,69,72,130,1,130,75,32,241,216,3,90,242,67,177,93,36,246,6,0,112,249,113,65,8,163,225,0,210,4,48,4,72,134,138,68,234,193,77,2,33,56,161,199,34,232,109,212,162,76,68,79,40,185,135,215,208,52,4,200,103,40,14,10,0,182,145,32,207,24,167,0,18,181,26,127,37,23,40,43,62,50,44,195,130,191,9,170,102,4,162,67,222,113,67,130,48,144,27,75,168,165,41,253,130,148,91,236,144,5,7,144,195,161,128,56,40,7,251,166,13,71,243,86,194,112,48,2,201,20,168,34,107,110,46,248,229,105,47,197,41,2,170,2,95,243,202,100,228,66,128,215,78,71,206,127,123,8,108,120,200,133,142,12,36,147,0,17,186,34,22,46,98,218,180,36,166,177,171,60,153,3,48,65,67,114,51,4,204,130,178,97,6,126,128,17,0,171,10,132,154,79,128,144,18,23,99,22,129,232,6,198,118,69,65,0,27,23,44,182,13,234,252,127,188,132,169,224,136,180,91,17,128,34,244,87,21,80,12,63,210,207,93,48,110,62,199,28,130,185,45,162,62,186,164,102,134,183,99,15,139,136,40,184,70,40,166,133,60,12,196,65,2,9,39,197,71,65,3,16,102,129,50,65,34,227,208,96,33,200,103,79,206,141,16,148,71,168,247,197,140,53,3,1,224,46,248,0,45,90,30,128,38,162,66,17,134,248,100,128,189,203,17,202,97,158,12,75,226,4,16,17,19,113,93,182,217,124,42,98,146,240,216,114,12,0,70,46,174,193,46,212,4,82,64,32,0,152,66,230,156,243,19,27,112,136,200,66,8,16,48,5,34,8,192,3,120,138,41,65,26,152,181,84,156,201,90,65,128,221,226,197,210,64,88,246,193,128,68,60,2,44,240,3,0,6,0,64,130,12,1,106,44,54,149,9,76,4,3,210,13,14,208,39,231,116,99,18,94,27,112,172,149,6,96,6,152,10,225,120,4,80,154,30,73,49,64,64,197,188,5,137,38,4,8,122,132,219,8,128,17,12,196,100,98,28,212,4,102,12,192,148,96,22,87,8,142,24,115,22,5,16,24,77,16,140,9,69,48,33,162,32,239,245,202,199,237,240,154,10,34,168,94,191,156,212,42,120,183,159,57,201,192,192,111,230,26,49,244,56,6,206,192,105,7,134,210,139,153,42,3,185,91,51,141,54,34,14,223,27,3,72,35,96,6,103,22,3,38,162,126,66,23,48,72,64,8,186,112,134,40,3,238,47,144,8,148,135,4,68,25,183,83,68,34,208,24,129,10,64,161,11,82,18,9,0,109,128,4,97,7,55,113,224,168,199,53,97,145,0,219,182,144,32,32,46,147,208,172,24,48,73,168,92,223,200,50,37,74,109,107,30,166,2,152,148,119,150,144,189,215,96,20,152,186,21,8,236,209,212,140,216,168,161,27,30,13,249,183,254,192,75,176,181,236,124,81,51,26,64,15,6,91,232,5,90,57,50,219,242,99,36,132,122,53,90,122,139,20,5,25,4,219,160,20,188,93,26,16,16,119,12,200,16,164,35,89,159,55,87,160,2,21,127,152,172,13,40,80,33,96,26,49,32,8,81,7,145,83,65,192,48,16,156,176,255,39,240,147,12,24,29,227,31,204,146,51,121,32,161,73,166,200,160,19,51,14,2,34,64,104,32,234,160,221,21,228,248,66,0,104,154,192,202,13,73,12,89,210,164,4,24,111,219,121,31,244,76,128,152,64,178,130,129,65,16,32,204,20,49,120,233,188,133,202,144,163,172,200,55,5,166,120,6,144,2,5,56,134,11,0,39,179,137,160,130,9,168,204,98,116,138,228,32,29,217,16,120,7,73,8,2,133,104,48,160,115,16,64,93,20,240,123,182,65,156,11,224,7,81,145,92,115,75,32,119,56,153,82
};
public static byte[] PINYIN_CODE = new byte[]
{
205,191,41,121,121,171,168,68,208,111,110,193,50,96,96,107,131,242,67,129,134,103,41,47,111,50,80,193,63,129,134,144,3,107,16,118,179,166,0,107,245,0,92,59,163,114,111,36,184,139,0,0,0,90,130,104,126,90,228,196,164,15,102,131,139,57,102,131,9,30,112,144,201,52,130,102,134,125,93,85,124,252,187,55,112,90,15,39,133,53,114,68,177,15,60,6,125,49,38,57,148,85,102,250,147,95,55,235,61,96,98,65,225,129,48,101,45,253,30,252,123,193,95,94,95,143,75,254,101,65,130,131,149,0,178,18,136,0,85,250,171,126,109,252,109,92,92,72,122,250,28,53,13,110,121,132,121,124,158,104,104,95,146,107,107,26,189,135,63,140,166,164,36,49,169,94,1,45,83,69,105,129,56,167,180,172,196,179,34,52,148,41,60,16,180,138,41,124,41,127,194,203,219,101,66,240,136,30,85,5,118,131,49,0,0,253,0,107,80,91,133,254,149,49,249,41,122,158,131,150,113,126,85,98,65,82,93,203,84,254,10,175,177,254,87,20,83,126,75,165,114,47,73,37,60,195,139,37,52,141,141,59,126,129,228,88,75,222,19,136,69,123,86,2,8,118,28,102,177,165,95,41,0,0,0,0,129,71,0,180,0,0,112,57,41,132,59,175,224,106,85,54,32,149,96,37,93,139,149,104,0,249,100,167,87,126,59,129,54,20,14,68,41,137,107,129,130,130,1,129,131,253,60,104,16,50,35,175,169,30,195,106,61,58,197,250,0,18,128,129,252,196,222,104,95,131,106,80,1,100,250,196,128,107,46,129,158,247,62,41,0,197,110,133,106,252,167,167,22,180,0,52,184,199,126,232,184,133,95,72,112,169,85,136,51,171,0,41,0,136,180,100,169,136,36,134,77,52,123,220,111,178,162,0,87,0,139,89,176,107,131,106,110,107,88,224,20,32,163,139,45,35,80,49,5,4,0,0,111,183,169,117,181,59,141,0,163,163,136,167,169,6,209,111,176,0,252,48,124,91,111,111,252,232,95,34,41,250,144,104,141,85,95,86,111,155,164,156,48,85,81,104,250,121,38,0,156,145,156,145,43,30,0,106,91,90,111,252,89,104,96,84,59,135,232,121,64,124,95,239,85,89,121,35,0,171,41,104,145,111,47,124,133,132,48,21,84,250,21,21,77,139,252,38,27,38,27,134,54,54,169,55,111,169,107,57,57,49,131,129,203,203,102,203,51,101,65,38,57,33,95,98,41,24,141,243,251,3,52,1,114,171,104,89,133,103,24,127,58,129,103,0,114,81,40,18,64,135,33,106,66,51,126,52,104,58,72,132,171,18,72,131,131,41,232,73,136,106,1,104,30,148,148,102,98,65,126,126,102,6,129,104,232,126,73,104,89,84,105,205,193,193,2,151,72,111,14,14,14,241,241,14,32,191,0,0,241,0,130,126,23,205,75,98,80,15,87,139,205,114,3,71,0,59,238,139,76,53,14,24,0,191,54,41,111,75,115,131,57,24,184,205,169,69,15,33,249,180,126,26,126,195,180,4,67,39,63,200,141,190,250,244,207,250,60,87,43,86,14,212,0,90,37,70,1,250,106,85,111,101,3,99,148,1,99,70,58,184,1,101,114,114,46,46,132,19,109,59,46,166,216,74,83,107,68,133,3,18,120,197,52,126,66,112,30,143,43,78,83,57,85,75,190,3,250,32,234,112,252,84,84,98,49,17,100,132,38,84,0,0,60,133,38,252,196,102,79,1,136,19,142,119,58,5,129,15,15,93,81,134,84,93,141,121,0,250,86,95,95,0,104,83,114,112,113,100,37,36,58,110,75,121,128,250,205,16,193,57,197,84,39,65,14,30,133,238,235,141,115,101,177,193,120,87,232,169,182,25,87,80,121,203,193,41,139,117,75,75,76,115,169,196,104,90,85,110,65,133,128,102,126,100,49,157,137,139,90,3,104,130,134,5,20,126,196,12,143,41,166,110,102,119,93,82,191,49,121,246,48,83,133,52,222,37,176,237,20,250,49,216,139,113,136,38,167,96,97,90,235,200,58,101,129,109,105,13,97,178,180,58,183,90,247,120,136,106,135,134,104,126,126,149,37,106,80,120,131,101,174,49,129,80,92,90,22,144,133,106,84,85,147,136,132,183,0,3,70,104,204,167,104,196,5,135,247,80,89,90,119,95,52,157,61,255,139,80,135,17,246,98,93,133,106,124,201,128,76,251,234,84,4,177,104,130,136,252,132,133,131,39,143,27,0,126,129,177,32,127,121,224,98,135,174,3,80,129,142,112,9,190,143,110,85,20,71,124,119,104,249,107,163,114,164,112,169,99,90,84,169,46,87,104,111,69,165,111,135,130,39,82,193,54,37,238,87,37,71,159,245,220,112,136,89,35,217,71,109,89,87,68,77,52,74,140,28,64,169,46,49,167,46,61,72,165,162,171,80,83,114,124,63,0,20,131,127,27,90,105,92,40,44,99,47,127,103,151,78,112,75,70,115,83,139,93,172,127,57,143,65,255,61,140,144,85,89,250,102,109,112,175,60,135,240,114,33,41,250,84,38,180,210,139,61,49,167,133,240,85,50,65,241,58,111,216,111,180,93,196,136,176,182,106,53,4,123,111,217,37,243,46,121,112,162,127,1,100,252,65,198,133,106,196,12,112,81,11,85,1,112,148,129,35,112,27,180,144,72,0,131,197,241,85,111,112,37,37,16,124,136,131,227,111,3,68,4,72,87,124,20,83,83,63,80,81,17,90,27,80,96,94,100,119,96,196,148,191,107,100,110,119,198,92,193,116,127,207,158,39,77,234,193,171,250,250,193,65,50,80,24,72,197,95,203,95,129,239,131,131,121,87,88,104,106,126,39,134,131,125,59,111,14,200,39,71,38,109,139,134,0,3,133,0,106,60,178,128,112,208,8,110,5,45,172,32,100,46,220,144,78,39,189,107,161,158,0,131,95,179,107,92,0,0,247,135,107,60,112,56,112,171,102,195,142,38,148,58,57,76,177,101,26,201,124,39,104,182,187,249,80,169,23,84,85,81,253,27,39,52,104,131,51,114,94,106,15,127,52,52,216,57,39,17,80,235,41,41,236,82,25,199,115,65,114,125,85,144,63,133,107,90,134,122,96,144,61,63,54,14,133,126,108,106,95,178,133,100,35,189,107,46,184,163,181,89,18,59,111,94,121,14,16,133,132,15Line truncated
};
}
}
@@ -0,0 +1,15 @@
namespace WxOrder.Framework.Commons.pinyin.Data
{
public static class PinyinCode3
{
public static byte[] PINYIN_CODE_PADDING = new byte[]
{
176,9,83,102,151,4,40,15,197,134,34,208,132,7,1,50,66,128,4,45,104,73,121,252,179,147,135,146,136,110,52,222,137,42,137,128,202,46,52,188,148,25,143,53,9,143,186,1,104,1,128,3,140,76,112,150,114,97,11,206,76,152,80,208,19,140,225,33,1,59,226,34,169,11,219,193,172,131,48,70,244,154,216,192,106,173,222,189,32,194,242,107,155,33,31,12,78,113,59,136,234,35,20,200,27,14,55,187,162,0,16,67,169,209,97,184,60,75,157,12,233,125,130,194,230,145,11,53,36,96,33,8,50,235,129,12,136,52,98,194,226,192,56,85,192,58,20,37,11,4,198,46,44,211,11,64,192,209,126,4,131,74,72,104,130,80,5,142,213,230,51,196,190,230,151,235,159,222,129,40,159,184,79,66,168,98,36,119,24,217,92,28,233,89,144,234,146,168,163,100,21,23,118,160,98,244,75,204,96,12,248,34,177,237,5,138,103,41,110,154,26,109,17,247,66,89,226,215,166,24,93,182,178,147,199,7,111,69,46,36,40,4,1,208,62,15,66,153,162,1,50,0,37,212,88,180,5,50,128,166,103,219,36,148,11,101,185,239,204,82,89,69,24,56,153,197,4,253,103,227,35,79,128,15,71,207,232,225,14,192,233,64,72,4,137,42,10,194,106,165,12,0,23,181,177,144,84,172,16,52,145,68,34,2,38,48,138,220,205,136,1,36,81,202,181,129,37,8,48,119,130,231,110,86,4,96,67,213,59,134,64,98,128,154,112,125,19,72,236,10,33,0,18,1,108,236,105,50,28,208,99,168,15,246,83,183,19,1,203,69,205,15,165,50,167,122,97,79,45,96,102,13,164,84,163,198,162,10,154,4,148,146,161,84,105,222,118,193,108,178,16,82,161,218,154,227,38,224,25,105,89,99,94,202,138,138,201,22,42,111,144,100,16,5,220,193,112,132,136,163,83,160,65,92,222,71,85,66,97,226,97,32,53,238,110,60,108,12,216,143,112,23,240,215,169,48,170,68,64,196,145,134,40,40,3,100,2,209,164,181,74,64,66,214,3,106,123,162,46,111,23,10,186,130,16,80,40,49,8,112,66,156,48,137,34,162,164,128,84,42,33,20,1,8,21,164,140,37,67,137,96,33,5,44,19,135,48,149,94,203,210,41,11,17,203,0,162,17,74,20,136,8,164,200,0,128,66,144,76,128,39,1,1,192,151,202,61,11,33,136,96,78,7,25,32,219,164,2,125,226,56,26,3,66,41,241,108,51,193,252,190,137,229,150,151,7,39,154,63,34,74,178,48,167,36,192,241,64,39,86,137,29,131,20,0,0,38,33,96,41,151,203,161,10,232,50,236,2,42,68,32,25,194,83,218,156,123,236,106,23,3,0,57,32,20,230,8,158,252,3,18,153,176,62,20,40,105,27,178,176,50,95,2,136,117,128,177,79,62,89,198,174,128,167,218,64,40,147,151,53,181,145,202,79,213,8,33,20,89,130,200,41,118,63,241,89,145,237,120,7,145,113,228,20,109,128,111,37,243,173,160,179,220,186,89,225,230,156,11,112,56,141,216,94,33,32,152,0,28,64,52,168,193,226,217,7,68,6,16,2,131,12,192,173,64,23,105,41,137,24,133,136,9,42,207,68,128,190,56,12,212,64,8,200,176,18,186,56,74,74,217,203,128,53,122,153,29,21,78,80,96,152,1,6,209,240,96,49,1,14,47,73,33,174,72,8,196,208,66,167,96,122,244,119,12,39,13,80,181,20,6,41,228,140,32,16,209,130,149,128,207,161,78,139,108,202,187,12,185,123,233,67,6,23,84,226,252,20,193,7,24,242,228,144,17,34,65,17,0,99,8,192,20,2,129,37,232,160,119,104,73,130,58,42,132,225,147,255,240,51,245,40,64,29,113,80,180,69,196,27,66,33,49,0,0,0,0,0,0,0,0,0,0,0,0
};
public static byte[] PINYIN_CODE = new byte[]
{
235,249,249,206,48,85,86,114,132,131,129,21,25,79,196,114,55,131,201,0,95,177,85,102,164,15,82,92,55,39,60,183,17,56,87,11,102,107,14,145,108,0,94,27,0,163,0,129,169,24,164,111,0,107,203,66,94,84,69,136,240,3,171,49,85,246,3,135,46,134,80,73,26,111,104,129,173,14,180,95,21,127,183,253,189,100,168,129,16,108,112,63,52,180,35,33,63,199,98,189,20,63,55,129,28,96,111,121,5,196,179,51,134,23,247,132,196,49,219,126,142,106,131,217,41,106,158,36,121,30,152,252,187,25,120,253,71,171,175,152,2,14,169,80,129,252,38,83,195,232,32,65,98,133,19,19,167,111,254,41,122,131,188,114,10,110,4,180,10,126,77,64,85,141,149,82,17,86,158,47,19,99,95,90,141,59,84,69,49,89,85,109,81,34,250,131,114,55,176,111,86,82,129,119,49,62,167,96,114,111,85,114,20,114,2,80,126,80,129,48,88,181,199,104,168,132,24,37,253,171,148,112,56,64,60,97,14,126,55,171,83,68,89,102,90,41,131,147,119,22,91,98,102,7,51,41,98,74,245,80,214,40,188,17,243,58,250,119,36,131,80,216,107,95,49,89,250,82,131,95,158,134,15,63,196,163,135,118,198,2,255,87,0,232,87,52,184,104,95,90,169,104,161,167,133,63,133,241,63,102,203,124,16,83,51,59,73,2,254,80,177,126,41,95,114,0,169,136,136,2,175,119,96,36,162,128,75,84,19,19,250,118,180,52,73,190,114,245,111,98,129,137,96,203,0,52,137,0,220,20,9,104,87,111,139,171,171,106,253,107,178,70,80,113,176,4,102,83,196,163,158,163,129,59,0,167,167,69,87,133,80,158,126,123,169,129,196,167,123,183,129,210,180,131,0,0,167,5,89,104,181,194,17,121,121,180,230,184,133,89,252,41,121,95,55,90,95,95,180,121,111,114,133,139,109,10,100,126,126,158,8,85,41,39,3,66,129,3,68,39,0,63,129,35,111,93,144,119,126,195,96,54,86,31,39,104,187,88,84,77,233,38,252,81,81,19,9,241,113,113,142,250,8,106,250,24,112,141,126,252,250,134,99,114,205,79,86,86,113,100,119,90,8,134,90,38,71,10,87,216,62,3,110,124,246,38,110,115,112,139,169,90,8,124,101,241,20,87,136,66,17,19,102,8,4,35,67,176,102,58,102,107,169,37,4,204,96,48,126,126,190,90,101,76,174,136,104,87,160,133,169,104,246,129,110,35,104,79,203,2,255,107,100,133,189,0,129,130,210,49,250,92,174,3,34,109,130,73,35,7,77,112,41,96,87,37,131,90,87,129,84,90,169,164,14,41,112,110,134,58,100,68,65,73,126,83,133,50,85,139,196,250,250,111,142,161,195,253,49,85,182,169,67,66,61,159,93,112,111,9,85,241,80,75,104,112,52,5,252,19,216,1,80,172,109,78,70,77,8,143,79,24,101,107,109,32,0,161,148,129,90,68,188,95,197,111,134,39,96,125,100,15,16,80,90,112,193,80,90,18,90,110,110,191,86,107,39,39,60,136,145,64,90,112,158,195,161,72,121,3,67,169,103,114,139,208,179,46,15,107,132,74,164,236,49,85,85,85,112,82,171,51,8,15,15,129,84,94,112,0,104,14,122,60,104,72,207,115,121,85,187,201,104,81,107,63,111,25,0,0,189,0,33,39,26,38,63,5,180,80,133,60,36,243,4,241,111,131,183,179,0,134,106,132,43,81,133,78,129,129,187,187,109,173,191,85,49,169,189,89,0,127,190,88,203,144,49,3,62,133,240,240,133,4,17,173,235,107,85,129,139,125,85,165,141,141,126,106,32,133,32,10,89,84,39,98,49,0,37,59,169,90,32,104,136,56,32,250,144,88,35,183,0,107,31,169,120,96,171,136,120,90,190,90,250,15,131,195,114,17,128,143,134,18,115,199,83,167,134,161,196,169,46,169,3,220,180,72,89,136,178,169,178,87,103,241,9,102,140,107,0,85,24,4,5,72,24,189,4,134,136,124,97,125,229,238,229,91,134,203,80,199,199,39,92,100,145,112,0,176,96,41,87,69,178,134,87,99,121,80,60,39,80,60,142,118,4,104,104,21,93,111,16,30,104,32,36,90,108,86,43,134,206,134,58,14,134,134,90,250,90,8,133,12,0,135,142,112,193,31,5,219,126,8,130,75,176,57,10,237,102,151,14,34,59,139,115,97,94,131,104,233,20,63,76,90,108,133,133,8,235,104,191,0,206,152,96,32,4,11,111,85,0,20,0,90,104,38,153,12,132,130,54,203,134,80,96,17,136,107,106,23,174,0,0,140,59,0,159,149,219,41,130,159,37,169,140,37,248,96,104,111,36,177,3,7,129,104,21,140,46,30,7,169,171,171,153,131,89,59,14,108,61,112,176,38,33,40,76,16,172,33,238,238,85,112,183,109,100,72,64,133,139,250,129,133,103,149,0,64,39,90,39,90,15,67,159,73,94,94,115,112,10,10,90,111,72,100,126,11,41,184,0,0,114,57,101,56,123,15,112,17,207,137,56,8,74,38,25,219,107,134,252,123,153,171,163,169,129,39,184,104,67,90,87,80,16,26,129,253,28,10,88,0,249,131,139,131,149,129,58,115,83,20,88,91,17,10,189,163,5,76,126,26,54,224,32,171,14,135,59,41,59,14,163,249,17,133,0,41,76,39,7,90,20,36,162,178,85,87,163,129,57,0,117,39,131,235,104,0,99,85,85,102,87,59,0,0,90,6,115,129,129,131,105,15,100,107,141,242,191,196,196,199,39,49,126,183,141,203,66,171,102,133,142,85,32,80,85,65,111,163,77,72,0,236,129,201,246,101,4,126,135,105,62,131,183,4,131,80,141,4,183,163,37,63,105,131,105,100,107,196,39,32,163,141,129,85,63,65,111,101,135,4,133,138,135,51,141,133,34,129,102,58,149,63,33,122,5,96,133,134,107,100,41,134,124,3,92,52,216,129,180,133,136,14,92,121,33,100,133,97,41,85,104,169,141,85,100,85,100,100,68,90,3,3,133,119,129,83,98,66,119,30,61,95,134,104,12,98,106,32,250,75,129,98,106,77,86,99,102,50,37,106,91,141,89,211,36,110,133,93,84,91,34,35,87,22,142,95,104,104,52,38,115,37,115,95,131,136,132,101,144,144,126,102,90,131,67,176,63,101,169,210,235,135,93,39,139,5,124,75,104,4,128,246,Line truncated
};
}
}
@@ -0,0 +1,69 @@
using System;
namespace WxOrder.Framework.Commons.pinyin.Data
{
public static class PinyinData
{
/// <summary>
/// 汉字 Unicode 编码最小值
/// </summary>
public static char MIN_VALUE = (char)19968;
/// <summary>
/// 汉字 Unicode 编码最小值
/// </summary>
public static char MAX_VALUE = (char)40869;
/// <summary>
/// 特殊的汉字“〇”,编码为 12295
/// </summary>
public static String PINYIN_12295 = "LING";
public static char CHAR_12295 = (char)12295;
public static int PINYIN_CODE_1_OFFSET = 7000;
public static int PINYIN_CODE_2_OFFSET = 7000 * 2;
public static int[] BIT_MASKS = new int[] { 1, 2, 4, 8, 16, 32, 64, 128 };
public static short PADDING_MASK = 256;
//CHECKSTYLE:OFF
public static string[] PINYIN_TABLE = new string[]{"", "A", "AI", "AN", "ANG", "AO", "BA", "BAI",
"BAN", "BANG", "BAO", "BEI", "BEN", "BENG", "BI", "BIAN", "BIAO", "BIE", "BIN", "BING",
"BO", "BU", "CA", "CAI", "CAN", "CANG", "CAO", "CE", "CEN", "CENG", "CHA", "CHAI",
"CHAN", "CHANG", "CHAO", "CHE", "CHEN", "CHENG", "CHI", "CHONG", "CHOU", "CHU", "CHUAI",
"CHUAN", "CHUANG", "CHUI", "CHUN", "CHUO", "CI", "CONG", "COU", "CU", "CUAN", "CUI",
"CUN", "CUO", "DA", "DAI", "DAN", "DANG", "DAO", "DE", "DENG", "DI", "DIA", "DIAN",
"DIAO", "DIE", "DING", "DIU", "DONG", "DOU", "DU", "DUAN", "DUI", "DUN", "DUO", "E",
"EI", "EN", "ER", "E^", "FA", "FAN", "FANG", "FEI", "FEN", "FENG", "FO", "FOU", "FU",
"GA", "GAI", "GAN", "GANG", "GAO", "GE", "GEI", "GEN", "GENG", "GONG", "GOU", "GU",
"GUA", "GUAI", "GUAN", "GUANG", "GUI", "GUN", "GUO", "HA", "HAI", "HAN", "HANG", "HAO",
"HE", "HEI", "HEN", "HENG", "HONG", "HOU", "HU", "HUA", "HUAI", "HUAN", "HUANG", "HUI",
"HUN", "HUO", "JI", "JIA", "JIAN", "JIANG", "JIAO", "JIE", "JIN", "JING", "JIONG",
"JIU", "JU", "JUAN", "JUE", "JUN", "KA", "KAI", "KAN", "KANG", "KAO", "KE", "KEN",
"KENG", "KONG", "KOU", "KU", "KUA", "KUAI", "KUAN", "KUANG", "KUI", "KUN", "KUO", "LA",
"LAI", "LAN", "LANG", "LAO", "LE", "LEI", "LENG", "LI", "LIA", "LIAN", "LIANG", "LIAO",
"LIE", "LIN", "LING", "LIU", "LONG", "LOU", "LU", "LUAN", "LUN", "LUO", "LV", "LVE",
"M", "MA", "MAI", "MAN", "MANG", "MAO", "ME", "MEI", "MEN", "MENG", "MI", "MIAN",
"MIAO", "MIE", "MIN", "MING", "MIU", "MO", "MOU", "MU", "NA", "NAI", "NAN", "NANG",
"NAO", "NE", "NEI", "NEN", "NENG", "NG", "NI", "NIAN", "NIANG", "NIAO", "NIE", "NIN",
"NING", "NIU", "NONG", "NOU", "NU", "NUAN", "NUO", "NV", "NVE", "O", "OU", "PA", "PAI",
"PAN", "PANG", "PAO", "PEI", "PEN", "PENG", "PI", "PIAN", "PIAO", "PIE", "PIN", "PING",
"PO", "POU", "PU", "QI", "QIA", "QIAN", "QIANG", "QIAO", "QIE", "QIN", "QING", "QIONG",
"QIU", "QU", "QUAN", "QUE", "QUN", "RAN", "RANG", "RAO", "RE", "REN", "RENG", "RI",
"RONG", "ROU", "RU", "RUAN", "RUI", "RUN", "RUO", "SA", "SAI", "SAN", "SANG", "SAO",
"SE", "SEN", "SENG", "SHA", "SHAI", "SHAN", "SHANG", "SHAO", "SHE", "SHEI", "SHEN",
"SHENG", "SHI", "SHOU", "SHU", "SHUA", "SHUAI", "SHUAN", "SHUANG", "SHUI", "SHUN",
"SHUO", "SI", "SONG", "SOU", "SU", "SUAN", "SUI", "SUN", "SUO", "TA", "TAI", "TAN",
"TANG", "TAO", "TE", "TENG", "TI", "TIAN", "TIAO", "TIE", "TING", "TONG", "TOU", "TU",
"TUAN", "TUI", "TUN", "TUO", "WA", "WAI", "WAN", "WANG", "WEI", "WEN", "WENG", "WO",
"WU", "XI", "XIA", "XIAN", "XIANG", "XIAO", "XIE", "XIN", "XING", "XIONG", "XIU", "XU",
"XUAN", "XUE", "XUN", "YA", "YAN", "YANG", "YAO", "YE", "YI", "YIAO", "YIN", "YING",
"YO", "YONG", "YOU", "YU", "YUAN", "YUE", "YUN", "ZA", "ZAI", "ZAN", "ZANG", "ZAO",
"ZE", "ZEI", "ZEN", "ZENG", "ZHA", "ZHAI", "ZHAN", "ZHANG", "ZHAO", "ZHE", "ZHEI",
"ZHEN", "ZHENG", "ZHI", "ZHONG", "ZHOU", "ZHU", "ZHUA", "ZHUAI", "ZHUAN", "ZHUANG",
"ZHUI", "ZHUN", "ZHUO", "ZI", "ZONG", "ZOU", "ZU", "ZUAN", "ZUI", "ZUN", "ZUO"};
//CHECKSTYLE:ON
}
}
+169
View File
@@ -0,0 +1,169 @@
using System;
using System.Collections.Generic;
using System.Text;
using WxOrder.Framework.Commons.pinyin.Data;
namespace WxOrder.Framework.Commons.pinyin
{
public static class Engine
{
public static string[] PinyinFromDict(string wordInDict, List<IPinyinDict> pinyinDictSet)
{
if (pinyinDictSet != null)
{
foreach (IPinyinDict dict in pinyinDictSet)
{
if (dict != null && dict.Words() != null && dict.Words().Contains(wordInDict))
{
return dict.ToPinyin(wordInDict);
}
}
}
throw new ArgumentException("No pinyin dict contains word: " + wordInDict);
}
/// <summary>
/// 获取给定的字符串的拼音
/// </summary>
/// <param name="inputStr"></param>
/// <param name="trie"></param>
/// <param name="pinyinDictList"></param>
/// <param name="separator"></param>
/// <returns></returns>
public static string ToPinyin(string inputStr, string trie, List<IPinyinDict> pinyinDictList, string separator)
{
if (inputStr == null || inputStr.Length == 0)
{
return inputStr;
}
if (trie == null)
{
// 没有提供字典或选择器,按单字符转换输出
var builder1 = new StringBuilder();
for (int i = 0; i < inputStr.Length; i++)
{
builder1.Append(GetPinyinByChar(inputStr[i]));
if (i != inputStr.Length - 1)
{
builder1.Append(separator);
}
}
return builder1.ToString();
}
return null;
//List<Emit> selectedEmits = selector.select(trie.parseText(inputStr));
//Collections.sort(selectedEmits, EMIT_COMPARATOR);
//StringBuffer resultPinyinStrBuf = new StringBuffer();
//int nextHitIndex = 0;
//for (int i = 0; i < inputStr.length();)
//{
// // 首先确认是否有以第i个字符作为begin的hit
// if (nextHitIndex < selectedEmits.size() && i == selectedEmits.get(nextHitIndex).getStart())
// {
// // 有以第i个字符作为begin的hit
// String[] fromDicts = pinyinFromDict(selectedEmits.get(nextHitIndex).getKeyword(), pinyinDictList);
// for (int j = 0; j < fromDicts.length; j++)
// {
// resultPinyinStrBuf.append(fromDicts[j].toUpperCase());
// if (j != fromDicts.length - 1)
// {
// resultPinyinStrBuf.append(separator);
// }
// }
// i = i + selectedEmits.get(nextHitIndex).size();
// nextHitIndex++;
// }
// else
// {
// // 将第i个字符转为拼音
// resultPinyinStrBuf.append(Pinyin.toPinyin(inputStr.charAt(i)));
// i++;
// }
// if (i != inputStr.length())
// {
// resultPinyinStrBuf.append(separator);
// }
//}
//return resultPinyinStrBuf.toString();
}
private static int GetPinyinCode(char c)
{
int offset = c - PinyinData.MIN_VALUE;
if (0 <= offset && offset < PinyinData.PINYIN_CODE_1_OFFSET)
{
// 前 7000 个汉字
return decodeIndex(PinyinCode1.PINYIN_CODE_PADDING, PinyinCode1.PINYIN_CODE, offset);
}
else if (PinyinData.PINYIN_CODE_1_OFFSET <= offset && offset < PinyinData.PINYIN_CODE_2_OFFSET)
{
// 7000 ~ 14000 个汉字
return decodeIndex(PinyinCode2.PINYIN_CODE_PADDING, PinyinCode2.PINYIN_CODE, offset - PinyinData.PINYIN_CODE_1_OFFSET);
}
else
{
// 14000 之后的汉字
return decodeIndex(PinyinCode3.PINYIN_CODE_PADDING, PinyinCode3.PINYIN_CODE, offset - PinyinData.PINYIN_CODE_2_OFFSET);
}
}
private static short decodeIndex(byte[] paddings, byte[] indexes, int offset)
{
//CHECKSTYLE:OFF
int index1 = offset / 8;
int index2 = offset % 8;
short realIndex;
realIndex = (short)(indexes[offset] & 0xff);
//CHECKSTYLE:ON
if ((paddings[index1] & PinyinData.BIT_MASKS[index2]) != 0)
{
realIndex = (short)(realIndex | PinyinData.PADDING_MASK);
}
return realIndex;
}
/// <summary>
/// 判断是否是汉字
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public static bool IsChinese(char c)
{
return (PinyinData.MIN_VALUE <= c && c <= PinyinData.MAX_VALUE && GetPinyinCode(c) > 0) || PinyinData.CHAR_12295 == c;
}
/// <summary>
/// 获取单个汉字的完整拼音
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public static string GetPinyinByChar(char c)
{
if (IsChinese(c))
{
if (c == PinyinData.CHAR_12295)
{
return PinyinData.PINYIN_12295;
}
else
{
return PinyinData.PINYIN_TABLE[GetPinyinCode(c)];
}
}
else
{
return c.ToString();
}
}
}
}
@@ -0,0 +1,16 @@
using System.Collections.Generic;
namespace WxOrder.Framework.Commons.pinyin
{
public interface IPinyinDict
{
/// <summary>
/// 转换文本为到拼音
/// </summary>
/// <param name="word"></param>
/// <returns></returns>
string[] ToPinyin(string word);
List<string> Words();
}
}
@@ -0,0 +1,34 @@
using System.Collections.Generic;
using System.Linq;
namespace WxOrder.Framework.Commons.pinyin
{
public abstract class PinyinDict : IPinyinDict
{
public abstract Dictionary<string, string[]> Mapping();
public string[] ToPinyin(string word)
{
var mappingResult = Mapping();
if (mappingResult == null)
{
return null;
}
if (mappingResult.TryGetValue(word, out var result))
{
return result;
}
return null;
}
public List<string> Words()
{
var mappingResult = Mapping();
if (mappingResult == null)
{
return null;
}
return mappingResult.Keys.Select(key => key).ToList();
}
}
}
@@ -0,0 +1,51 @@
using System.Linq;
namespace WxOrder.Framework.Commons.pinyin
{
public static class PinyinHelper
{
/// <summary>
/// 判断给定字符是否是中文
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public static bool IsChinese(char c)
{
return Engine.IsChinese(c);
}
/// <summary>
/// 获取单个字符的拼音
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public static string GetPinyin(char c)
{
return Engine.GetPinyinByChar(c);
}
/// <summary>
/// 获取文本的拼音
/// </summary>
/// <param name="str">要获取拼音的文本</param>
/// <param name="separator">单个拼音分隔符</param>
/// <returns></returns>
public static string GetPinyin(string str, string separator = " ")
{
return Engine.ToPinyin(str, null, null, separator);
}
/// <summary>
/// 获取拼音首字母
/// </summary>
/// <param name="str"></param>
/// <param name="separator">拼音分割符,默认空字符串(不分割)</param>
/// <returns></returns>
public static string GetPinyinInitials(string str, string separator = "")
{
var result = GetPinyin(str, "|");
// 修复:获取首字母时字符串中含有|字符会报超出索引范围,https://github.com/hstarorg/TinyPinyin.Net/issues/5
return string.Join(separator, result.Split('|').Select(x => !string.IsNullOrWhiteSpace(x) && x.Length > 0 ? x.Substring(0, 1) : x).ToArray());
}
}
}
+2 -1
View File
@@ -1,8 +1,9 @@
using System;
using System.Net;
using System.Text;
using WxOrder.Framework.Helpers;
namespace WxOrder.Framework.Helpers
namespace WxOrder.Framework.PDDAPI
{
/// <summary>
/// 拼多多API请求类