macad.presentation解析events,helpers,multicover,resourcesextention

本文主要是介绍macad.presentation解析events,helpers,multicover,resourcesextention,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.events

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;namespace Macad.Presentation
{// 该类用于启用鼠标水平滚轮支持public static class MouseHorizontalWheelEnabler{// 当为 true 时,将尝试自动在父窗口/弹出窗口/上下文菜单中启用水平滚轮支持,程序员无需调用该方法,默认为 truepublic static bool AutoEnableMouseHorizontalWheelSupport = true;// 已经挂钩的窗口集合private static readonly HashSet<IntPtr> _HookedWindows = new HashSet<IntPtr>();// 启用指定窗口内所有控件的水平滚轮支持public static void EnableMouseHorizontalWheelSupport([NotNull] Window window){if (window == null){throw new ArgumentNullException(nameof(window));}if (window.IsLoaded){// 在窗口加载后获取句柄IntPtr handle = new WindowInteropHelper(window).Handle;EnableMouseHorizontalWheelSupport(handle);}else{// 在窗口加载后再次尝试获取句柄window.Loaded += (sender, args) =>{IntPtr handle = new WindowInteropHelper(window).Handle;EnableMouseHorizontalWheelSupport(handle);};}}// 启用指定弹出窗口内所有控件的水平滚轮支持public static void EnableMouseHorizontalWheelSupport([NotNull] System.Windows.Controls.Primitives.Popup popup){if (popup == null){throw new ArgumentNullException(nameof(popup));}if (popup.IsOpen){// 在弹出窗口打开后获取句柄EnableMouseHorizontalWheelSupport(GetObjectParentHandle(popup.Child).Value);}// 当弹出窗口打开时再次尝试获取句柄popup.Opened += (sender, args) =>{EnableMouseHorizontalWheelSupport(GetObjectParentHandle(popup.Child).Value);};}// 启用指定上下文菜单内所有控件的水平滚轮支持public static void EnableMouseHorizontalWheelSupport([NotNull] ContextMenu contextMenu){if (contextMenu == null){throw new ArgumentNullException(nameof(contextMenu));}if (contextMenu.IsOpen){EnableMouseHorizontalWheelSupport(GetObjectParentHandle(contextMenu).Value);}// 当上下文菜单打开时再次尝试获取句柄contextMenu.Opened += (sender, args) =>{EnableMouseHorizontalWheelSupport(GetObjectParentHandle(contextMenu).Value);};}// 获取对象的父级窗口句柄private static IntPtr? GetObjectParentHandle([NotNull] DependencyObject depObj){if (depObj == null){throw new ArgumentNullException(nameof(depObj));}var presentationSource = PresentationSource.FromDependencyObject(depObj) as HwndSource;return presentationSource?.Handle;}// 启用指定句柄内所有控件的水平滚轮支持public static bool EnableMouseHorizontalWheelSupport(IntPtr handle){if (_HookedWindows.Contains(handle)){return true;}_HookedWindows.Add(handle);HwndSource source = HwndSource.FromHwnd(handle);if (source == null){return false;}source.AddHook(WndProcHook);return true;}// 窗口消息处理回调函数private static IntPtr WndProcHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled){// 处理水平滚轮消息switch (msg){case Win32.WM_MOUSEHWHEEL:HandleMouseHorizontalWheel(wParam);break;}return IntPtr.Zero;}// 处理水平滚轮事件private static void HandleMouseHorizontalWheel(IntPtr wParam){int tilt = -Win32.HiWord(wParam);if (tilt == 0){return;}IInputElement element = Mouse.DirectlyOver;if (element == null){return;}if (!(element is UIElement)){element = PresentationHelper.FindLogicalParent<UIElement>(element as DependencyObject);}if (element == null){return;}var ev = new MouseHorizontalWheelEventArgs(Mouse.PrimaryDevice, Environment.TickCount, tilt){RoutedEvent = PreviewMouseHorizontalWheelEvent};// 触发预览事件element.RaiseEvent(ev);if (ev.Handled){return;}// 再次触发事件ev.RoutedEvent = MouseHorizontalWheelEvent;element.RaiseEvent(ev);}// Win32 APIprivate static class Win32{public const int WM_MOUSEHWHEEL = 0x020E;public static int GetIntUnchecked(IntPtr value){return IntPtr.Size == 8 ? unchecked((int)value.ToInt64()) : value.ToInt32();}public static int HiWord(IntPtr ptr){return unchecked((short)((uint)GetIntUnchecked(ptr) >> 16));}}// 鼠标水平滚轮事件public static readonly RoutedEvent MouseHorizontalWheelEvent =EventManager.RegisterRoutedEvent("MouseHorizontalWheel", RoutingStrategy.Bubble, typeof(MouseHorizontalWheelEventHandler),typeof(MouseHorizontalWheelEnabler));public static void AddMouseHorizontalWheelHandler(DependencyObject d, MouseHorizontalWheelEventHandler handler){var uie = d as UIElement;if (uie != null){uie.AddHandler(MouseHorizontalWheelEvent, handler);if (AutoEnableMouseHorizontalWheelSupport){EnableMouseHorizontalWheelSupportForParentOf(uie);}}}public static void RemoveMouseHorizontalWheelHandler(DependencyObject d, MouseHorizontalWheelEventHandler handler){var uie = d as UIElement;uie?.RemoveHandler(MouseHorizontalWheelEvent, handler);}// 预览鼠标水平滚轮事件public static readonly RoutedEvent PreviewMouseHorizontalWheelEvent =EventManager.RegisterRoutedEvent("PreviewMouseHorizontalWheel", RoutingStrategy.Tunnel, typeof(RoutedEventHandler),typeof(MouseHorizontalWheelEnabler));public static void AddPreviewMouseHorizontalWheelHandler(DependencyObject d, RoutedEventHandler handler){var uie = d as UIElement;if (uie != null){uie.AddHandler(PreviewMouseHorizontalWheelEvent, handler);if (AutoEnableMouseHorizontalWheelSupport){EnableMouseHorizontalWheelSupportForParentOf(uie);}}}public static void RemovePreviewMouseHorizontalWheelHandler(DependencyObject d, RoutedEventHandler handler){var uie = d as UIElement;uie?.RemoveHandler(PreviewMouseHorizontalWheelEvent, handler);}// 启用指定 UI 元素及其父级控件的水平滚轮支持public static void EnableMouseHorizontalWheelSupportForParentOf(UIElement uiElement){if (uiElement is Window){EnableMouseHorizontalWheelSupport((Window)uiElement);}else if (uiElement is Popup){EnableMouseHorizontalWheelSupport((System.Windows.Controls.Primitives.Popup)uiElement);}else if (uiElement is ContextMenu){EnableMouseHorizontalWheelSupport((ContextMenu)uiElement);}else{IntPtr? parentHandle = GetObjectParentHandle(uiElement);if (parentHandle != null){EnableMouseHorizontalWheelSupport(parentHandle.Value);}// 监听父级窗口变化事件PresentationSource.AddSourceChangedHandler(uiElement, PresenationSourceChangedHandler);}}// 父级窗口变化事件处理函数private static void PresenationSourceChangedHandler(object sender, SourceChangedEventArgs sourceChangedEventArgs){var src = sourceChangedEventArgs.NewSource as HwndSource;if (src != null){EnableMouseHorizontalWheelSupport(src.Handle);}}}
}

这段代码实现了一个功能,即在 WPF 应用程序中启用鼠标水平滚轮的支持。它提供了一些静态方法和事件,以便在窗口、弹出窗口、上下文菜单以及其子控件上启用鼠标水平滚轮的支持。同时,它还定义了鼠标水平滚轮事件以及预览事件,以便程序员可以在应用程序中处理这些事件。

2.

using System;
using System.Windows.Input;namespace Macad.Presentation
{// 该类定义了鼠标水平滚轮事件的委托public delegate void MouseHorizontalWheelEventHandler(object sender, MouseHorizontalWheelEventArgs e);// 定义了鼠标水平滚轮事件参数类,继承自 MouseEventArgspublic class MouseHorizontalWheelEventArgs : MouseEventArgs{// 鼠标滚轮滚动的距离public int Delta { get; }// 构造函数,传入鼠标设备、时间戳和滚动距离public MouseHorizontalWheelEventArgs(MouseDevice mouse, int timestamp, int delta): base(mouse, timestamp){Delta = delta;}// 调用事件处理程序protected override void InvokeEventHandler(Delegate genericHandler, object genericTarget){MouseHorizontalWheelEventHandler handler = (MouseHorizontalWheelEventHandler)genericHandler;handler(genericTarget, this);}}
}

这段代码定义了一个名为 MouseHorizontalWheelEventArgs 的类,用于表示鼠标水平滚轮事件的参数。它继承自 MouseEventArgs 类,因此可以从中获取鼠标设备和时间戳等信息,并新增了一个属性 Delta 用于表示鼠标滚轮滚动的距离。此外,还定义了一个委托 MouseHorizontalWheelEventHandler,用于处理鼠标水平滚轮事件。

3.helpers

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;namespace Macad.Presentation
{// 该类定义了一个全局事件处理器,用于处理在文本框中按下 Enter 键后将焦点移到下一个 UI 元素的逻辑public static class GlobalEventHandler{// 标志是否已注册事件处理器static bool _IsRegistered;// 初始化方法,用于注册事件处理器public static void Init(){if (!_IsRegistered){// 注册 TextBox 类的 KeyDown 事件处理器EventManager.RegisterClassHandler(typeof(TextBox), TextBox.KeyDownEvent, new KeyEventHandler(_TextBox_KeyDown));_IsRegistered = true;}}// TextBox 类的 KeyDown 事件处理器static void _TextBox_KeyDown(object sender, KeyEventArgs e){// 当按下 Enter 键且文本框不接受多行输入时,移动焦点到下一个 UI 元素if (e.Key == Key.Enter & (sender as TextBox)?.AcceptsReturn == false) _MoveToNextUIElement(e);}// 移动焦点到下一个 UI 元素的方法static void _MoveToNextUIElement(KeyEventArgs e){// 创建一个 FocusNavigationDirection 对象,并设置为 NextFocusNavigationDirection focusDirection = FocusNavigationDirection.Next;// 创建一个 TraversalRequest 对象,并传入 FocusNavigationDirection 对象TraversalRequest request = new TraversalRequest(focusDirection);// 获取当前具有键盘焦点的元素UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;// 改变键盘焦点if (elementWithFocus != null){if (elementWithFocus.MoveFocus(request)) e.Handled = true;}}}
}

这段代码定义了一个名为 GlobalEventHandler 的静态类,其中包含了一个初始化方法 Init() 和一个用于处理文本框按下 Enter 键后移动焦点的方法 _TextBox_KeyDown(),以及一个辅助方法 _MoveToNextUIElement()。通过注册类处理程序,当 TextBox 控件的 KeyDown 事件发生时,将调用 _TextBox_KeyDown() 方法来处理按键事件,如果按下的是 Enter 键且文本框不接受多行输入,则调用 _MoveToNextUIElement() 方法来移动焦点到下一个 UI 元素。

4.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Media;namespace Macad.Presentation
{// 这个类提供了一些有关颜色处理的帮助方法public static class ColorHelper {// 在静态构造函数中初始化标准颜色、扩展颜色和六边形颜色static ColorHelper(){_CreateStandardColors();_CreateExtendedColors();_CreateHexagonColors();}// 创建标准颜色列表public static Color[] StandardColors;static void _CreateStandardColors(){// 将一组标准颜色存储在 StandardColors 数组中StandardColors = new []{Brushes.White.Color,Brushes.Red.Color,Brushes.Orange.Color,Brushes.Yellow.Color,Brushes.LightGreen.Color,Brushes.Green.Color,Brushes.LightBlue.Color,Brushes.Blue.Color,Brushes.SteelBlue.Color,Brushes.DarkKhaki.Color};}// 创建扩展颜色列表const float _Percent10 = 0.90f;const float _Percent25 = 0.75f;const float _Percent40 = 0.60f;const float _Percent55 = 0.45f;const float _Percent70 = 0.30f;public static Color[] ExtendedColors;static void _CreateExtendedColors(){// 将一组扩展颜色存储在 ExtendedColors 数组中ExtendedColors = new []{// 一些基本颜色Brushes.White.Color,Brushes.DarkRed.Color,Brushes.Green.Color,Brushes.Indigo.Color,Brushes.Blue.Color,Brushes.Red.Color,Brushes.SlateGray.Color,Brushes.DarkKhaki.Color,Brushes.Yellow.Color,Brushes.Orange.Color,// 使用比例对基本颜色进行调节,并存储在 ExtendedColors 数组中// 每个基本颜色都会根据给定的比例进行调节,生成一系列新的颜色};}// 创建六边形颜色列表public class HexagonColor{public Color Color { get; private set; }public int Row { get; private set; }public int Column { get; private set; }public HexagonColor(Color color, int row, int column){Color = color;Row = row;Column = column;}// 重写 ToString 方法以返回包含颜色、行和列信息的字符串public override string ToString(){return $"{Row},{Column},{Color}";}}public static HexagonColor[] HexagonColors;static void _CreateHexagonColors(){// 将一组六边形颜色存储在 HexagonColors 数组中HexagonColors = new[]{// 六边形颜色的初始化};}//--------------------------------------------------------------------------------------------------// 创建六边形颜色项public static HexagonColor[] CreateHexagonColorItems(IList<Common.Color> colors, int cols){var result = new HexagonColor[colors.Count];int col = 0, row = 0;for(int index=0; index<colors.Count; index++){// 将 Common.Color 转换为 WPF 颜色并存储在 HexagonColor 数组中result[index] = new HexagonColor( colors[index].ToWpfColor(), row, col);col++;if (col >= cols){row++;col = 0;}}return result;}//--------------------------------------------------------------------------------------------------#region Color Conversion// 定义未定义颜色public static Color UndefinedColor { get; private set; }// 将颜色转换为十六进制表示形式public static string ColorToHex(Color color){return string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", color.A, color.R, color.G, color.B);}// 计算两个颜色之间的差异public static double ColorDifference(Color c1, Color c2){// 计算颜色之间的欧氏距离double dr = (c1.R - c2.R) / 255.0;double dg = (c1.G - c2.G) / 255.0;double db = (c1.B - c2.B) / 255.0;return Math.Sqrt(dr * dr + dg * dg + db * db);}#endregion#region Private Methods// 创建未定义颜色static ColorHelper(){UndefinedColor = Color.FromArgb(0, 0, 0, 0);}#endregion}
}

这个代码文件主要提供了一些颜色处理的帮助方法和数据结构。其中,包括创建标准颜色、扩展颜色和六边形颜色列表,以及将颜色转换为十六进制表示形式、计算颜色之间的差异等功能。

5.

using System.Windows.Threading;namespace Macad.Presentation
{// Helper class for managing UI thread message processingpublic class DispatcherHelper{// Allows the UI thread to process pending messages asynchronouslypublic static void DoEvents(){// Create a new DispatcherFramevar frame = new DispatcherFrame();// Begin invoking a delegate asynchronously at the specified priorityDispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(_ExitFrame), frame);// Push the created frame onto the current Dispatcher's stackDispatcher.PushFrame(frame);}//--------------------------------------------------------------------------------------------------// Allows the UI thread to process pending messages synchronouslypublic static void DoEventsSync(){// Create a new DispatcherFramevar frame = new DispatcherFrame();// Invoke a delegate synchronously at the specified priorityDispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background,new DispatcherOperationCallback(_ExitFrame),frame);// Push the created frame onto the current Dispatcher's stackDispatcher.PushFrame(frame);}//--------------------------------------------------------------------------------------------------// Callback method to exit the DispatcherFramestatic object _ExitFrame(object frame){// Set the Continue property of the frame to false to exit the frame((DispatcherFrame)frame).Continue = false;return null;}//--------------------------------------------------------------------------------------------------}
}

整段代码实现了一个用于处理 UI 线程消息的辅助类 DispatcherHelper。该类提供了两个静态方法 DoEvents()DoEventsSync()

  • DoEvents() 方法允许 UI 线程异步处理待处理的消息,并在消息处理完毕后返回。
  • DoEventsSync() 方法允许 UI 线程同步处理待处理的消息,并在消息处理完毕后返回。

这两个方法通过 Dispatcher 类来管理 UI 线程的消息队列,并使用 DispatcherFrame 来控制消息的处理。

6.

using System.Text;
using System.Windows.Input;
using Macad.Common.Interop;namespace Macad.Presentation
{// Helper class for handling input-related operationspublic static class InputHelper{// Stores simulated modifier keyspublic static ModifierKeys SimulatedModifiers { get; set; } = ModifierKeys.None;//--------------------------------------------------------------------------------------------------// Checks if the provided KeyEventArgs contains the specified modifier keypublic static bool HasModifier(KeyEventArgs args, ModifierKeys modifier){// Check if the keyboard device's modifiers include the specified modifier or if it's simulatedreturn args.KeyboardDevice.Modifiers.HasFlag(modifier) || SimulatedModifiers.HasFlag(modifier);}//--------------------------------------------------------------------------------------------------// Converts the KeyEventArgs to a text representation of the pressed keypublic static string ConvertKeyToText(KeyEventArgs args){var sb = new StringBuilder();byte[] bKeyState  = new byte[255];// Set the state of Shift, Control, and Alt keys in the key state arrayif (HasModifier(args, ModifierKeys.Shift))bKeyState[0x10] = 0x80;if (HasModifier(args, ModifierKeys.Control))bKeyState[0x11] = 0x80;if (HasModifier(args, ModifierKeys.Alt))bKeyState[0x12] = 0x80;// Get the virtual key code from the pressed Keyvar vkey = KeyInterop.VirtualKeyFromKey(args.Key);// Map the virtual key code to the corresponding scan codeuint lScanCode = Win32Api.MapVirtualKey((uint)vkey, Win32Api.MapVirtualKeyMapTypes.MAPVK_VK_TO_VSC);// Convert the virtual key to Unicode textWin32Api.ToUnicode((uint)vkey, lScanCode, bKeyState, sb, 5, 0);// Return the Unicode text representing the pressed keyreturn sb.ToString();}}
}

这段代码实现了一个用于处理输入相关操作的辅助类 InputHelper。该类提供了两个静态方法:

  • HasModifier(KeyEventArgs args, ModifierKeys modifier):检查提供的 KeyEventArgs 中是否包含指定的修改键(Shift、Control、Alt)。
  • ConvertKeyToText(KeyEventArgs args):将提供的 KeyEventArgs 转换为表示按下键的文本表示形式。

此外,该类还包含了一个静态属性 SimulatedModifiers,用于存储模拟的修改键。

7.

using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;namespace Macad.Presentation
{// Helper class for various presentation-related taskspublic static class PresentationHelper{// Private field to cache the result of the IsInDesignMode propertyprivate static bool? _IsInDesignMode;// Property to determine if the application is in design modepublic static bool IsInDesignMode{get{// If the IsInDesignMode property hasn't been evaluated yetif (!_IsInDesignMode.HasValue){var prop = DesignerProperties.IsInDesignModeProperty;// Get the default value of the IsInDesignMode property from the metadata of FrameworkElement_IsInDesignMode = (bool)DependencyPropertyDescriptor.FromProperty(prop, typeof(FrameworkElement)).Metadata.DefaultValue;}return _IsInDesignMode.Value;}}//--------------------------------------------------------------------------------------------------// Constant for double zeropublic static readonly double DoubleZero = 0D;//--------------------------------------------------------------------------------------------------// Finds the visual parent of the specified type for the provided DependencyObjectpublic static T FindVisualParent<T>(DependencyObject child) where T : DependencyObject{DependencyObject parentObject = VisualTreeHelper.GetParent(child);if (parentObject == null) return null;T parent = parentObject as T;if (parent != null)return parent;elsereturn FindVisualParent<T>(parentObject);}//--------------------------------------------------------------------------------------------------// Finds the logical parent of the specified type for the provided DependencyObjectpublic static T FindLogicalParent<T>(DependencyObject child) where T : DependencyObject{DependencyObject parentObject = LogicalTreeHelper.GetParent(child);if (parentObject == null) return null;T parent = parentObject as T;if (parent != null)return parent;elsereturn FindLogicalParent<T>(parentObject);}//--------------------------------------------------------------------------------------------------// Forces focus on the specified FrameworkElementpublic static void ForceFocus(FrameworkElement element){if (!element.Focus()){// If focus couldn't be set immediately, schedule focus setting on the dispatcher threadelement.Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() => element.Focus()));}}//--------------------------------------------------------------------------------------------------// Finds the visual child of the specified type for the provided DependencyObjectpublic static T FindVisualChild<T>(DependencyObject visual) where T : DependencyObject{for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++){var child = VisualTreeHelper.GetChild(visual, i);T correctlyTyped = child as T;if (correctlyTyped != null){return correctlyTyped;}T descendent = FindVisualChild<T>(child);if (descendent != null){return descendent;}}return null;}//--------------------------------------------------------------------------------------------------}
}

这段代码实现了一个用于处理界面呈现相关任务的辅助类 PresentationHelper。该类提供了以下功能:

  • IsInDesignMode:检查应用程序是否处于设计模式。
  • DoubleZero:常量,表示双精度浮点数零。
  • FindVisualParent<T>:查找指定类型的 Visual 父级。
  • FindLogicalParent<T>:查找指定类型的逻辑父级。
  • ForceFocus:强制将焦点设置到指定的 FrameworkElement。
  • FindVisualChild<T>:查找指定类型的 Visual 子级。

这些方法可用于在 WPF 应用程序中执行与界面元素相关的操作,如查找父级、设置焦点等。

8.

using System;
using System.Windows.Input;namespace Macad.Presentation
{// Helper class for temporarily changing the mouse cursor to a wait cursor// Source: https://stackoverflow.com/questions/3480966/display-hourglass-when-application-is-busypublic sealed class WaitCursor : IDisposable{readonly Cursor _PreviousCursor;// Constructorpublic WaitCursor(){// Save the current cursor_PreviousCursor = Mouse.OverrideCursor;// Set the mouse cursor to the wait cursorMouse.OverrideCursor = Cursors.Wait;}// Dispose method to restore the previous cursor when done#region IDisposable Memberspublic void Dispose(){// Restore the previous cursorMouse.OverrideCursor = _PreviousCursor;}#endregion}
}

这段代码实现了一个辅助类 WaitCursor,用于临时将鼠标光标更改为等待光标。它通过实现 IDisposable 接口,当实例被释放时自动恢复先前的鼠标光标状态。

9.multiconverter

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;namespace Macad.Presentation
{// Converter class for performing AND operation on boolean values[ContentProperty("MultiConverter")][ValueConversion(typeof(bool), typeof(bool))]public class BooleanAndMultiConverter : MultiConverterMarkupExtension<BooleanAndMultiConverter>{// Convert method to perform AND operation on boolean valuespublic override object Convert(object[] values, Type targetType, object parameter, CultureInfo culture){// Iterate through the input valuesforeach (object value in values){// Check if the value is a booleanif (value is bool){// If any value is false, return falseif ((bool)value == false){return false;}}}// If all values are true, return truereturn true;}}
}

这段代码定义了一个名为 BooleanAndMultiConverter 的转换器类,用于执行布尔值的 AND 操作。它通过实现 IValueConverter 接口和 MultiConverterMarkupExtension 类来提供转换功能。Convert 方法遍历输入的布尔值数组,如果有任何一个值为 false,则返回 false;否则返回 true。

10.

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;namespace Macad.Presentation
{// 定义一个名为 BooleanAndToVisibleCollapsedMultiConverter 的转换器类// 该转换器用于执行布尔值的 AND 操作,并将结果转换为 Visibility 枚举类型[ContentProperty("MultiConverter")][ValueConversion(typeof(bool), typeof(bool))]public class BooleanAndToVisibleCollapsedMultiConverter : MultiConverterMarkupExtension<BooleanAndToVisibleCollapsedMultiConverter>{// 转换方法,执行布尔值的 AND 操作并转换为 Visibility 类型public override object Convert(object[] values, Type targetType, object parameter, CultureInfo culture){// 遍历输入的值数组foreach (object value in values){// 检查值是否为布尔类型if (value is bool boolValue){// 如果值为 false,则返回 Visibility.Collapsedif (!boolValue){return Visibility.Collapsed;}}}// 如果所有值均为 true,则返回 Visibility.Visiblereturn Visibility.Visible;}}
}

这段代码定义了一个名为 BooleanAndToVisibleCollapsedMultiConverter 的转换器类,用于执行布尔值的 AND 操作,并将结果转换为 Visibility 枚举类型。转换方法遍历输入的布尔值数组,如果有任何一个值为 false,则返回 Visibility.Collapsed;否则返回 Visibility.Visible。

11.

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;namespace Macad.Presentation
{// 定义一个名为 BooleanOrMultiConverter 的转换器类// 该转换器用于执行布尔值的 OR 操作,并将结果转换为布尔类型[ContentProperty("MultiConverter")][ValueConversion(typeof(bool), typeof(bool))]public class BooleanOrMultiConverter : MultiConverterMarkupExtension<BooleanOrMultiConverter>{// 转换方法,执行布尔值的 OR 操作并转换为布尔类型public override object Convert(object[] values, Type targetType, object parameter, CultureInfo culture){// 遍历输入的值数组foreach (object value in values){// 检查值是否为布尔类型if (value is bool){// 如果有任何一个值为 true,则返回 trueif ((bool)value == true){return true;}}}// 如果所有值均为 false,则返回 falsereturn false;}}
}

这段代码定义了一个名为 BooleanOrMultiConverter 的转换器类,用于执行布尔值的 OR 操作,并将结果转换为布尔类型。转换方法遍历输入的布尔值数组,如果有任何一个值为 true,则返回 true;否则返回 false。

12.

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;namespace Macad.Presentation
{// 定义一个名为 BooleanOrToVisibleCollapsedMultiConverter 的转换器类// 该转换器用于将多个布尔值进行 OR 操作,并将结果转换为 Visibility 枚举类型[ContentProperty("MultiConverter")][ValueConversion(typeof(bool), typeof(bool))]public class BooleanOrToVisibleCollapsedMultiConverter : MultiConverterMarkupExtension<BooleanOrToVisibleCollapsedMultiConverter>{// 转换方法,执行布尔值的 OR 操作并转换为 Visibility 枚举类型public override object Convert(object[] values, Type targetType, object parameter, CultureInfo culture){// 遍历输入的值数组foreach (object value in values){// 检查值是否为布尔类型if (value is bool boolValue){// 如果有任何一个值为 true,则返回 Visibleif (boolValue){return Visibility.Visible;}}}// 如果所有值均为 false,则返回 Collapsedreturn Visibility.Collapsed;}}
}

这段代码定义了一个名为 BooleanOrToVisibleCollapsedMultiConverter 的转换器类,用于将多个布尔值进行 OR 操作,并将结果转换为 Visibility 枚举类型。转换方法遍历输入的布尔值数组,如果有任何一个值为 true,则返回 Visibility.Visible;否则返回 Visibility.Collapsed

13.

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;namespace Macad.Presentation
{// 通过链接提供了更多关于如何使值转换器在标记中更易访问的信息// 基类public abstract class MultiConverterMarkupExtension<T> : MarkupExtension, IMultiValueConverter where T : class, new(){// 保护的静态实例字段protected static T _Instance = null;// 通过标记扩展提供值的方法public override object ProvideValue(IServiceProvider serviceProvider){// 如果实例为空,则创建一个新实例if (_Instance == null){_Instance = new T();}// 返回实例return _Instance;}#region IMultiValueConverter Members// 虚方法,用于将值转换为目标类型public virtual object Convert(object[] values, Type targetType, object parameter, CultureInfo culture){// 抛出不支持的操作异常throw new NotSupportedException();}// 虚方法,用于将目标值转换为源值public virtual object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture){// 抛出不支持的操作异常throw new NotSupportedException();}#endregion}
}
  • MultiConverterMarkupExtension 是一个抽象类,用于简化在 XAML 中使用多值转换器。
  • 通过继承 MarkupExtension 类,它可以作为标记扩展使用。
  • 通过实现 IMultiValueConverter 接口,它可以用于多值转换。
  • 提供了一个静态字段 _Instance,用于存储单例实例。
  • ProvideValue 方法返回单例实例,并在需要时创建新实例。
  • ConvertConvertBack 方法用于执行值的转换,这些方法在基类中都抛出了不支持的操作异常,因为它们应该在具体的子类中进行实现。

14.

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;namespace Macad.Presentation
{// 使用 ContentProperty 属性指定 MultiConverter 属性作为内容属性public class MultiValueConverterAdapter : MultiConverterMarkupExtension<MultiValueConverterAdapter>{// 公共属性,用于设置转换器public IValueConverter Converter { get; set; }// 上次使用的参数private object lastParameter;// 转换方法,将输入值转换为目标类型public override object Convert(object[] values, Type targetType, object parameter, CultureInfo culture){// 如果转换器为空,则返回第一个值(用于设计时)if (Converter == null) return values[0];// 如果有多个值,则保存最后一个参数if (values.Length > 1) lastParameter = values[1];// 调用转换器的 Convert 方法进行转换return Converter.Convert(values[0], targetType, lastParameter, culture);}// 转换回方法,将目标值转换回源值public override object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture){// 如果转换器为空,则返回值(用于设计时)if (Converter == null) return new object[] { value };// 调用转换器的 ConvertBack 方法进行转换return new object[] { Converter.ConvertBack(value, targetTypes[0], lastParameter, culture) };}}
}
  • MultiValueConverterAdapter 类是 MultiConverterMarkupExtension 的具体实现,用于将普通的 IValueConverter 转换器适配为多值转换器。
  • 通过 ContentProperty 特性,指定了 MultiConverter 属性作为内容属性,这意味着在 XAML 中可以直接将转换器放在标签的内容中。
  • 提供了一个公共属性 Converter,用于设置要使用的转换器。
  • Convert 方法将输入值转换为目标类型,并在需要时传递参数给转换器。
  • ConvertBack 方法将目标值转换回源值,并在需要时传递参数给转换器。
  • 为了支持设计时,当转换器为空时,直接返回输入值或输出值。

15.

using System;
using System.Globalization;
using System.Windows.Markup;namespace Macad.Presentation
{// 使用 ContentProperty 属性指定 MultiConverter 属性作为内容属性public class StringFormatMultiConverter : MultiConverterMarkupExtension<StringFormatMultiConverter>{// 转换方法,将输入值按照指定格式转换为字符串public override object Convert(object[] values, Type targetType, object parameter, CultureInfo culture){// 如果参数为空,返回错误提示信息if (parameter == null){return "ConverterParameter must not be null.";}// 使用 String.Format 方法将值按照指定格式转换为字符串return String.Format(parameter as String, values);}}
}
  • StringFormatMultiConverter 类是 MultiConverterMarkupExtension 的具体实现,用于根据指定的格式将多个输入值转换为字符串。
  • 通过 ContentProperty 特性,指定了 MultiConverter 属性作为内容属性,这意味着在 XAML 中可以直接将转换器放在标签的内容中。
  • 转换方法 Convert 使用 String.Format 方法将输入值按照指定格式转换为字符串。
  • 如果参数为空,则返回错误提示信息。

16.

using System;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media;
using Macad.Common;namespace Macad.Presentation
{// 图标资源扩展类,继承自 MarkupExtension 类public class IconResourceExtension : MarkupExtension{// 图标名称属性,用于指定要加载的图标资源[ConstructorArgument("iconName")] public string IconName { get; set; }// 构造函数,用于创建 IconResourceExtension 实例public IconResourceExtension() { }// 带参数的构造函数,用于初始化 IconName 属性public IconResourceExtension(string iconName){IconName = iconName;}// 提供值的方法,用于解析图标名称并返回对应的图像资源public override object ProvideValue(IServiceProvider serviceProvider){// 如果图标名称为空,则返回 nullif (IconName.IsNullOrEmpty())return null;// 从应用程序资源中查找对应名称的图标资源var drawing = Application.Current?.FindResource("Icon_" + IconName) as Drawing;// 如果找不到对应的图标资源,则返回 nullif (drawing == null)return null;// 创建 DrawingImage 对象,并冻结以提高性能var drawingImage = new DrawingImage(drawing);drawingImage.Freeze();return drawingImage;}}
}
  • IconResourceExtension 类继承自 MarkupExtension 类,用于在 XAML 中将图标名称解析为对应的图像资源。
  • 类中包含一个 IconName 属性,用于指定要加载的图标资源的名称。
  • 提供了两个构造函数,一个是无参构造函数,另一个是带参数的构造函数,用于初始化 IconName 属性。
  • ProvideValue 方法用于解析图标名称并返回对应的图像资源,在方法中首先检查图标名称是否为空,然后从应用程序资源中查找对应名称的图标资源,最后创建 DrawingImage 对象并冻结以提高性能。

这篇关于macad.presentation解析events,helpers,multicover,resourcesextention的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/903697

相关文章

Spring Boot 整合 SSE的高级实践(Server-Sent Events)

《SpringBoot整合SSE的高级实践(Server-SentEvents)》SSE(Server-SentEvents)是一种基于HTTP协议的单向通信机制,允许服务器向浏览器持续发送实... 目录1、简述2、Spring Boot 中的SSE实现2.1 添加依赖2.2 实现后端接口2.3 配置超时时

Python使用getopt处理命令行参数示例解析(最佳实践)

《Python使用getopt处理命令行参数示例解析(最佳实践)》getopt模块是Python标准库中一个简单但强大的命令行参数处理工具,它特别适合那些需要快速实现基本命令行参数解析的场景,或者需要... 目录为什么需要处理命令行参数?getopt模块基础实际应用示例与其他参数处理方式的比较常见问http

Python利用ElementTree实现快速解析XML文件

《Python利用ElementTree实现快速解析XML文件》ElementTree是Python标准库的一部分,而且是Python标准库中用于解析和操作XML数据的模块,下面小编就来和大家详细讲讲... 目录一、XML文件解析到底有多重要二、ElementTree快速入门1. 加载XML的两种方式2.

Java的栈与队列实现代码解析

《Java的栈与队列实现代码解析》栈是常见的线性数据结构,栈的特点是以先进后出的形式,后进先出,先进后出,分为栈底和栈顶,栈应用于内存的分配,表达式求值,存储临时的数据和方法的调用等,本文给大家介绍J... 目录栈的概念(Stack)栈的实现代码队列(Queue)模拟实现队列(双链表实现)循环队列(循环数组

java解析jwt中的payload的用法

《java解析jwt中的payload的用法》:本文主要介绍java解析jwt中的payload的用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解析jwt中的payload1. 使用 jjwt 库步骤 1:添加依赖步骤 2:解析 JWT2. 使用 N

Python中__init__方法使用的深度解析

《Python中__init__方法使用的深度解析》在Python的面向对象编程(OOP)体系中,__init__方法如同建造房屋时的奠基仪式——它定义了对象诞生时的初始状态,下面我们就来深入了解下_... 目录一、__init__的基因图谱二、初始化过程的魔法时刻继承链中的初始化顺序self参数的奥秘默认

Java 正则表达式URL 匹配与源码全解析

《Java正则表达式URL匹配与源码全解析》在Web应用开发中,我们经常需要对URL进行格式验证,今天我们结合Java的Pattern和Matcher类,深入理解正则表达式在实际应用中... 目录1.正则表达式分解:2. 添加域名匹配 (2)3. 添加路径和查询参数匹配 (3) 4. 最终优化版本5.设计思

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

Java字符串处理全解析(String、StringBuilder与StringBuffer)

《Java字符串处理全解析(String、StringBuilder与StringBuffer)》:本文主要介绍Java字符串处理全解析(String、StringBuilder与StringBu... 目录Java字符串处理全解析:String、StringBuilder与StringBuffer一、St

Spring Boot循环依赖原理、解决方案与最佳实践(全解析)

《SpringBoot循环依赖原理、解决方案与最佳实践(全解析)》循环依赖指两个或多个Bean相互直接或间接引用,形成闭环依赖关系,:本文主要介绍SpringBoot循环依赖原理、解决方案与最... 目录一、循环依赖的本质与危害1.1 什么是循环依赖?1.2 核心危害二、Spring的三级缓存机制2.1 三