WPFUtils.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Media;
  10. using InABox.Core;
  11. using InABox.Wpf;
  12. using Image = System.Windows.Controls.Image;
  13. using System.Runtime.InteropServices;
  14. using System.Windows.Interop;
  15. namespace InABox.WPF;
  16. public class FuncTemplateSelector : DataTemplateSelector
  17. {
  18. public Func<object, DependencyObject, FrameworkElement?> TemplateFunc { get; set; }
  19. public FuncTemplateSelector(Func<object, DependencyObject, FrameworkElement?> templateFunc)
  20. {
  21. TemplateFunc = templateFunc;
  22. }
  23. public override DataTemplate SelectTemplate(object item, DependencyObject container)
  24. {
  25. return TemplateGenerator.CreateDataTemplate(() =>
  26. {
  27. return TemplateFunc(item, container);
  28. });
  29. }
  30. }
  31. public static class WPFUtils
  32. {
  33. public static void MoveToCenter(this Window window)
  34. {
  35. if (!GetCursorPos(out POINT cursorPoint))
  36. return;
  37. IntPtr mainWindow = MonitorFromPoint(new POINT() { x = 1, y = 1 }, MONITOR_DEFAULTTO.MONITOR_DEFAULTTONULL);
  38. IntPtr monitorHandle = MonitorFromPoint(cursorPoint, MONITOR_DEFAULTTO.MONITOR_DEFAULTTONULL);
  39. MONITORINFO monitorInfo = new() { cbSize = (uint)Marshal.SizeOf<MONITORINFO>() };
  40. if (!GetMonitorInfo(monitorHandle, ref monitorInfo))
  41. return;
  42. IntPtr windowHandle = new WindowInteropHelper(window).EnsureHandle();
  43. if (!GetWindowPlacement(windowHandle, out WINDOWPLACEMENT windowPlacement))
  44. return;
  45. int left = monitorInfo.rcWork.left + Math.Max(0, (int)((monitorInfo.rcWork.Width - windowPlacement.rcNormalPosition.Width) / 2D));
  46. int top = monitorInfo.rcWork.top + Math.Max(0, (int)((monitorInfo.rcWork.Height - windowPlacement.rcNormalPosition.Height) / 2D));
  47. windowPlacement.rcNormalPosition = new RECT(left, top, windowPlacement.rcNormalPosition.Width, windowPlacement.rcNormalPosition.Height);
  48. SetWindowPlacement(windowHandle, ref windowPlacement);
  49. }
  50. [DllImport("User32.dll", SetLastError = true)]
  51. [return: MarshalAs(UnmanagedType.Bool)]
  52. private static extern bool GetCursorPos(out POINT lpPoint);
  53. [DllImport("User32.dll")]
  54. private static extern IntPtr MonitorFromPoint(POINT pt, MONITOR_DEFAULTTO dwFlags);
  55. private enum MONITOR_DEFAULTTO : uint
  56. {
  57. MONITOR_DEFAULTTONULL = 0x00000000,
  58. MONITOR_DEFAULTTOPRIMARY = 0x00000001,
  59. MONITOR_DEFAULTTONEAREST = 0x00000002,
  60. }
  61. [DllImport("User32.dll")]
  62. [return: MarshalAs(UnmanagedType.Bool)]
  63. private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);
  64. [StructLayout(LayoutKind.Sequential)]
  65. private struct MONITORINFO
  66. {
  67. public uint cbSize;
  68. public RECT rcMonitor;
  69. public RECT rcWork;
  70. public uint dwFlags;
  71. }
  72. [DllImport("User32.dll", SetLastError = true)]
  73. [return: MarshalAs(UnmanagedType.Bool)]
  74. private static extern bool GetWindowPlacement(IntPtr hWnd, out WINDOWPLACEMENT lpwndpl);
  75. [DllImport("User32.dll", SetLastError = true)]
  76. [return: MarshalAs(UnmanagedType.Bool)]
  77. private static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
  78. [StructLayout(LayoutKind.Sequential)]
  79. private struct WINDOWPLACEMENT
  80. {
  81. public uint length;
  82. public uint flags;
  83. public uint showCmd;
  84. public POINT ptMinPosition;
  85. public POINT ptMaxPosition;
  86. public RECT rcNormalPosition;
  87. }
  88. [StructLayout(LayoutKind.Sequential)]
  89. private struct POINT
  90. {
  91. public int x;
  92. public int y;
  93. }
  94. [StructLayout(LayoutKind.Sequential)]
  95. private struct RECT
  96. {
  97. public int left;
  98. public int top;
  99. public int right;
  100. public int bottom;
  101. public int Width => right - left;
  102. public int Height => bottom - top;
  103. public RECT(int x, int y, int width, int height)
  104. {
  105. left = x;
  106. top = y;
  107. right = x + width;
  108. bottom = y + height;
  109. }
  110. }
  111. #region Setters/Triggers etc
  112. public static Style AddSetter(this Style style, DependencyProperty property, object value)
  113. {
  114. style.Setters.Add(new Setter(property, value));
  115. return style;
  116. }
  117. public static DataTrigger AddSetter(this DataTrigger trigger, DependencyProperty property, object value)
  118. {
  119. trigger.Setters.Add(new Setter(property, value));
  120. return trigger;
  121. }
  122. public static DataTrigger AddDataTrigger(this Style style)
  123. {
  124. var trigger = new DataTrigger();
  125. style.Triggers.Add(trigger);
  126. return trigger;
  127. }
  128. public static DataTrigger AddDataTrigger(this Style style, Binding binding, object value)
  129. {
  130. var trigger = new DataTrigger() { Binding = binding, Value = value };
  131. style.Triggers.Add(trigger);
  132. return trigger;
  133. }
  134. #endregion
  135. public static SolidColorBrush ToBrush(this System.Windows.Media.Color color, double opacity = 1.0)
  136. {
  137. return new SolidColorBrush(color) { Opacity = opacity };
  138. }
  139. #region Multi-Binding
  140. public static MultiBinding CreateMultiBinding(IMultiValueConverter? converter = null, string? format = null, object? parameter = null)
  141. {
  142. return new MultiBinding
  143. {
  144. Converter = converter,
  145. ConverterParameter = parameter,
  146. StringFormat = format
  147. };
  148. }
  149. public static MultiBinding AddBinding(this MultiBinding multi, BindingBase binding)
  150. {
  151. multi.Bindings.Add(binding);
  152. return multi;
  153. }
  154. #endregion
  155. #region Binding
  156. public static Binding CreateBinding<T, TProperty>(
  157. T source,
  158. Expression<Func<T, TProperty>> expression,
  159. IValueConverter? converter = null,
  160. string? format = null)
  161. {
  162. return new Binding(CoreUtils.GetFullPropertyName(expression, "_"))
  163. {
  164. Source = source,
  165. Converter = converter,
  166. StringFormat = format
  167. };
  168. }
  169. public static Binding CreateBinding<T, TProperty>(
  170. Expression<Func<T, TProperty>> expression,
  171. IValueConverter? converter = null,
  172. BindingMode mode = BindingMode.Default,
  173. string? format = null,
  174. RelativeSource? relativeSource = null)
  175. {
  176. return new Binding(CoreUtils.GetFullPropertyName(expression, "_"))
  177. {
  178. Converter = converter,
  179. StringFormat = format,
  180. Mode = mode,
  181. RelativeSource = relativeSource
  182. };
  183. }
  184. public static DataTrigger Bind<T, TProperty, TValue>(
  185. this DataTrigger trigger,
  186. T source,
  187. Expression<Func<T, TProperty>> expression,
  188. TValue value,
  189. IValueConverter<TProperty, TValue>? converter,
  190. string? format = null)
  191. {
  192. trigger.Binding = CreateBinding(source, expression, converter, format);
  193. trigger.Value = value;
  194. return trigger;
  195. }
  196. public static DataTrigger Bind<T, TProperty, TValue>(
  197. this DataTrigger trigger,
  198. Expression<Func<T, TProperty>> expression,
  199. TValue value,
  200. IValueConverter<TProperty, TValue>? converter,
  201. BindingMode mode = BindingMode.Default,
  202. string? format = null,
  203. RelativeSource? relativeSource = null)
  204. {
  205. trigger.Binding = CreateBinding(expression, converter, mode, format, relativeSource: relativeSource);
  206. trigger.Value = value;
  207. return trigger;
  208. }
  209. public static DataTrigger Bind<T, TProperty>(
  210. this DataTrigger trigger,
  211. T source,
  212. Expression<Func<T, TProperty>> expression,
  213. TProperty value,
  214. IValueConverter? converter = null,
  215. string? format = null)
  216. {
  217. trigger.Binding = CreateBinding(source, expression, converter, format);
  218. trigger.Value = value;
  219. return trigger;
  220. }
  221. public static DataTrigger Bind<T, TProperty>(
  222. this DataTrigger trigger,
  223. Expression<Func<T, TProperty>> expression,
  224. TProperty value,
  225. IValueConverter? converter = null,
  226. BindingMode mode = BindingMode.Default,
  227. string? format = null,
  228. RelativeSource? relativeSource = null)
  229. {
  230. trigger.Binding = CreateBinding(expression, converter, mode, format, relativeSource: relativeSource);
  231. trigger.Value = value;
  232. return trigger;
  233. }
  234. public static void Bind<T, TProperty>(
  235. this FrameworkElement element,
  236. DependencyProperty property,
  237. T source,
  238. Expression<Func<T, TProperty>> expression,
  239. IValueConverter? converter = null,
  240. string? format = null)
  241. {
  242. element.SetBinding(
  243. property,
  244. CreateBinding(source, expression, converter, format)
  245. );
  246. }
  247. public static void Bind<T, TProperty>(
  248. this FrameworkElement element,
  249. DependencyProperty property,
  250. Expression<Func<T, TProperty>> expression,
  251. IValueConverter? converter = null,
  252. BindingMode mode = BindingMode.Default,
  253. string? format = null,
  254. RelativeSource? relativeSource = null)
  255. {
  256. element.SetBinding(
  257. property,
  258. CreateBinding(expression, converter, mode, format, relativeSource: relativeSource)
  259. );
  260. }
  261. public static FrameworkElementFactory Bind<T, TProperty>(
  262. this FrameworkElementFactory element,
  263. DependencyProperty property,
  264. T source,
  265. Expression<Func<T, TProperty>> expression,
  266. IValueConverter? converter = null,
  267. string? format = null)
  268. {
  269. element.SetBinding(
  270. property,
  271. CreateBinding(source, expression, converter, format)
  272. );
  273. return element;
  274. }
  275. public static FrameworkElementFactory Bind<T, TProperty>(
  276. this FrameworkElementFactory element,
  277. DependencyProperty property,
  278. Expression<Func<T, TProperty>> expression,
  279. IValueConverter? converter = null,
  280. BindingMode mode = BindingMode.Default,
  281. string? format = null,
  282. RelativeSource? relativeSource = null)
  283. {
  284. element.SetBinding(
  285. property,
  286. CreateBinding(expression, converter, mode, format, relativeSource: relativeSource ?? RelativeSource.TemplatedParent)
  287. );
  288. return element;
  289. }
  290. #endregion
  291. #region Converters
  292. public static IMultiValueConverter WrapConverter(this IValueConverter converter, Func<object?[], object?> convert, Func<object?, object?[]?>? convertBack = null)
  293. {
  294. return new MultiFuncConverter(convert, convertBack, converter);
  295. }
  296. #endregion
  297. public static T? FindLogicalParent<T>(this DependencyObject dependencyObject)
  298. where T : DependencyObject
  299. {
  300. DependencyObject? parent = dependencyObject;
  301. do
  302. {
  303. parent = LogicalTreeHelper.GetParent(parent);
  304. } while(parent != null && parent is not T);
  305. return parent as T;
  306. }
  307. public static IEnumerable<T> FindVisualChildren<T>(this DependencyObject depObj, bool recursive = true)
  308. {
  309. if (depObj != null)
  310. for (var i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
  311. {
  312. var child = VisualTreeHelper.GetChild(depObj, i);
  313. if (child is null)
  314. continue;
  315. if (child is T t)
  316. yield return t;
  317. if (recursive)
  318. {
  319. foreach (var childOfChild in FindVisualChildren<T>(child))
  320. yield return childOfChild;
  321. }
  322. }
  323. }
  324. public static T? FindChild<T>(this DependencyObject parent, string childName)
  325. where T : FrameworkElement
  326. {
  327. return parent.FindVisualChildren<T>().FirstOrDefault(x => x.Name == childName);
  328. }
  329. #region Grid Children
  330. public static int GetRow(this Grid grid, DependencyObject dependencyObject)
  331. {
  332. while (true)
  333. {
  334. var parent = LogicalTreeHelper.GetParent(dependencyObject);
  335. if (parent == null)
  336. return -1;
  337. if (parent == grid)
  338. return Grid.GetRow(dependencyObject as UIElement);
  339. dependencyObject = parent;
  340. }
  341. }
  342. public static int GetRowSpan(this Grid grid, DependencyObject dependencyObject)
  343. {
  344. while (true)
  345. {
  346. var parent = LogicalTreeHelper.GetParent(dependencyObject);
  347. if (parent == null)
  348. return -1;
  349. if (parent == grid)
  350. return Grid.GetRowSpan(dependencyObject as UIElement);
  351. dependencyObject = parent;
  352. }
  353. }
  354. public static int GetColumn(this Grid grid, DependencyObject dependencyObject)
  355. {
  356. while (true)
  357. {
  358. var parent = LogicalTreeHelper.GetParent(dependencyObject);
  359. if (parent == null)
  360. return -1;
  361. if (parent == grid)
  362. return Grid.GetColumn(dependencyObject as UIElement);
  363. dependencyObject = parent;
  364. }
  365. }
  366. public static int GetColumnSpan(this Grid grid, DependencyObject dependencyObject)
  367. {
  368. while (true)
  369. {
  370. var parent = LogicalTreeHelper.GetParent(dependencyObject);
  371. if (parent == null)
  372. return -1;
  373. if (parent == grid)
  374. return Grid.GetColumnSpan(dependencyObject as UIElement);
  375. dependencyObject = parent;
  376. }
  377. }
  378. public static void SetGridPosition(this FrameworkElement element, int row, int column, int rowspan = 1, int colspan = 1)
  379. {
  380. element.SetValue(Grid.ColumnProperty, column);
  381. element.SetValue(Grid.ColumnSpanProperty, Math.Max(1, colspan));
  382. element.SetValue(Grid.RowProperty, row);
  383. element.SetValue(Grid.RowSpanProperty, Math.Max(1, rowspan));
  384. }
  385. public static Grid AddChild(this Grid grid, FrameworkElement element, int row, int column, int rowSpan = 1, int colSpan = 1)
  386. {
  387. element.SetGridPosition(row, column, rowSpan, colSpan);
  388. grid.Children.Add(element);
  389. return grid;
  390. }
  391. #endregion
  392. #region Grid Columns + Rows
  393. public static ColumnDefinition AddColumn(this Grid grid, GridUnitType type, double value = 1)
  394. {
  395. var colDef = new ColumnDefinition { Width = new GridLength(value, type) };
  396. grid.ColumnDefinitions.Add(colDef);
  397. return colDef;
  398. }
  399. public static ColumnDefinition AddColumn(this Grid grid, double value)
  400. {
  401. var colDef = new ColumnDefinition { Width = new GridLength(value) };
  402. grid.ColumnDefinitions.Add(colDef);
  403. return colDef;
  404. }
  405. public static RowDefinition AddRow(this Grid grid, GridUnitType type, double value = 1)
  406. {
  407. var rowDef = new RowDefinition { Height = new GridLength(value, type) };
  408. grid.RowDefinitions.Add(rowDef);
  409. return rowDef;
  410. }
  411. public static RowDefinition AddRow(this Grid grid, double value)
  412. {
  413. var rowDef = new RowDefinition { Height = new GridLength(value) };
  414. grid.RowDefinitions.Add(rowDef);
  415. return rowDef;
  416. }
  417. #endregion
  418. #region Menu Utils
  419. private static void ItemsControlInsert(ItemsControl menu, FrameworkElement item, int index)
  420. {
  421. if (index != -1)
  422. {
  423. menu.Items.Insert(index, item);
  424. }
  425. else
  426. {
  427. menu.Items.Add(item);
  428. }
  429. }
  430. private static MenuItem DoAddMenuItem(ItemsControl menu, string caption, Bitmap? image, bool enabled, int index = -1)
  431. {
  432. var item = new MenuItem { Header = caption, IsEnabled = enabled };
  433. if (image != null)
  434. item.Icon = new Image() { Source = enabled ? image.AsBitmapImage(24, 24) : image.AsGrayScale().AsBitmapImage(24, 24) };
  435. ItemsControlInsert(menu, item, index);
  436. return item;
  437. }
  438. private static MenuItem DoAddMenuItem(ItemsControl menu, string caption, Bitmap? image, Action? click, bool enabled, int index = -1)
  439. {
  440. var item = DoAddMenuItem(menu, caption, image, enabled, index);
  441. if (click != null)
  442. {
  443. item.Click += (o, e) =>
  444. {
  445. click();
  446. };
  447. }
  448. return item;
  449. }
  450. private static MenuItem DoAddMenuItem<T>(ItemsControl menu, string caption, Bitmap? image, T tag, Action<T> click, bool enabled, int index = -1)
  451. {
  452. var item = DoAddMenuItem(menu, caption, image, enabled, index);
  453. item.Tag = tag;
  454. item.Click += (o, e) =>
  455. {
  456. click((T)(o as MenuItem)!.Tag);
  457. };
  458. return item;
  459. }
  460. public delegate void CheckToggleAction(bool isChecked);
  461. public delegate void CheckToggleAction<T>(T tag, bool isChecked);
  462. private static MenuItem DoAddCheckItem(ItemsControl menu, string caption, CheckToggleAction click, bool isChecked, bool enabled, int index = -1)
  463. {
  464. var item = new MenuItem { Header = caption, IsEnabled = enabled, IsCheckable = true, IsChecked = isChecked };
  465. item.Click += (o, e) =>
  466. {
  467. click(item.IsChecked);
  468. };
  469. ItemsControlInsert(menu, item, index);
  470. return item;
  471. }
  472. private static MenuItem DoAddCheckItem<T>(ItemsControl menu, string caption, T tag, CheckToggleAction<T> click, bool isChecked, bool enabled, int index = -1)
  473. {
  474. var item = new MenuItem { Header = caption, IsEnabled = enabled, IsCheckable = true, IsChecked = isChecked };
  475. item.Tag = tag;
  476. item.Click += (o, e) =>
  477. {
  478. click((T)(o as MenuItem)!.Tag, item.IsChecked);
  479. };
  480. ItemsControlInsert(menu, item, index);
  481. return item;
  482. }
  483. private static Separator DoAddSeparator(ItemsControl menu, int index)
  484. {
  485. var separator = new Separator();
  486. ItemsControlInsert(menu, separator, index);
  487. return separator;
  488. }
  489. private static Separator? DoAddSeparatorIfNeeded(ItemsControl menu, int index)
  490. {
  491. if (menu.Items.Count == 0) return null;
  492. var lastIndex = index != -1 ? index - 1 : menu.Items.Count - 1;
  493. if (lastIndex < 0 || lastIndex >= menu.Items.Count) return null;
  494. var last = menu.Items[lastIndex];
  495. if (last is Separator) return null;
  496. var separator = new Separator();
  497. ItemsControlInsert(menu, separator, index);
  498. return separator;
  499. }
  500. private static void DoRemoveUnnecessarySeparators(ItemsControl menu)
  501. {
  502. while(menu.Items.Count > 0 && menu.Items[0] is Separator)
  503. {
  504. menu.Items.RemoveAt(0);
  505. }
  506. while(menu.Items.Count > 0 && menu.Items[^1] is Separator)
  507. {
  508. menu.Items.RemoveAt(menu.Items.Count - 1);
  509. }
  510. }
  511. public static Separator AddSeparator(this ContextMenu menu, int index = -1) => DoAddSeparator(menu, index);
  512. public static Separator AddSeparator(this MenuItem menu, int index = -1) => DoAddSeparator(menu, index);
  513. public static Separator? AddSeparatorIfNeeded(this ContextMenu menu, int index = -1) => DoAddSeparatorIfNeeded(menu, index);
  514. public static Separator? AddSeparatorIfNeeded(this MenuItem menu, int index = -1) => DoAddSeparatorIfNeeded(menu, index);
  515. public static void RemoveUnnecessarySeparators(this ContextMenu menu) => DoRemoveUnnecessarySeparators(menu);
  516. public static void RemoveUnnecessarySeparators(this MenuItem menu) => DoRemoveUnnecessarySeparators(menu);
  517. public static MenuItem AddItem(this ContextMenu menu, string caption, Bitmap? image, Action? click, bool enabled = true, int index = -1)
  518. => DoAddMenuItem(menu, caption, image, click, enabled, index);
  519. public static MenuItem AddItem(this MenuItem menu, string caption, Bitmap? image, Action? click, bool enabled = true, int index = -1)
  520. => DoAddMenuItem(menu, caption, image, click, enabled, index);
  521. public static MenuItem AddItem<T>(this ContextMenu menu, string caption, Bitmap? image, T tag, Action<T> click, bool enabled = true, int index = -1)
  522. => DoAddMenuItem(menu, caption, image, tag, click, enabled, index);
  523. public static MenuItem AddItem<T>(this MenuItem menu, string caption, Bitmap? image, T tag, Action<T> click, bool enabled = true, int index = -1)
  524. => DoAddMenuItem(menu, caption, image, tag, click, enabled, index);
  525. public static MenuItem AddCheckItem(this ContextMenu menu, string caption, CheckToggleAction click, bool isChecked = false, bool enabled = true, int index = -1)
  526. => DoAddCheckItem(menu, caption, click, isChecked, enabled, index);
  527. public static MenuItem AddCheckItem<T>(this ContextMenu menu, string caption, T tag, CheckToggleAction<T> click, bool isChecked = false, bool enabled = true, int index = -1)
  528. => DoAddCheckItem(menu, caption, tag, click, isChecked, enabled, index);
  529. #endregion
  530. }