DynamicGrid.cs 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.ComponentModel;
  6. using System.Data;
  7. using System.Diagnostics;
  8. using System.Drawing;
  9. using System.Globalization;
  10. using System.Linq;
  11. using System.Linq.Expressions;
  12. using System.Reflection;
  13. using System.Threading.Tasks;
  14. using System.Windows;
  15. using System.Windows.Controls;
  16. using System.Windows.Data;
  17. using System.Windows.Input;
  18. using System.Windows.Media;
  19. using System.Windows.Media.Imaging;
  20. using System.Windows.Threading;
  21. using InABox.Clients;
  22. using InABox.Core;
  23. using InABox.Scripting;
  24. using InABox.WPF;
  25. using NPOI.SS.Formula.Functions;
  26. using Syncfusion.Data;
  27. using Syncfusion.UI.Xaml.Grid;
  28. using Syncfusion.UI.Xaml.Grid.Cells;
  29. using Syncfusion.UI.Xaml.Grid.Helpers;
  30. using Syncfusion.Windows.Controls.Cells;
  31. using Syncfusion.Windows.Controls.Grid;
  32. using Syncfusion.Windows.Shared;
  33. using Syncfusion.Windows.Tools.Controls;
  34. using Syncfusion.XPS;
  35. using Color = System.Drawing.Color;
  36. using DataRow = System.Data.DataRow;
  37. using FilterElement = Syncfusion.UI.Xaml.Grid.FilterElement;
  38. using Geometry = System.Windows.Media.Geometry;
  39. using GridCellToolTipOpeningEventArgs = Syncfusion.UI.Xaml.Grid.GridCellToolTipOpeningEventArgs;
  40. using GridFilterEventArgs = Syncfusion.UI.Xaml.Grid.GridFilterEventArgs;
  41. using GridSelectionMode = Syncfusion.UI.Xaml.Grid.GridSelectionMode;
  42. using Image = System.Windows.Controls.Image;
  43. using Path = System.Windows.Shapes.Path;
  44. using Point = System.Windows.Point;
  45. using Resources = InABox.DynamicGrid.Properties.Resources;
  46. using RowColumnIndex = Syncfusion.UI.Xaml.ScrollAxis.RowColumnIndex;
  47. using SolidColorBrush = System.Windows.Media.SolidColorBrush;
  48. using Transform = System.Windows.Media.Transform;
  49. using VirtualizingCellsControl = Syncfusion.UI.Xaml.Grid.VirtualizingCellsControl;
  50. namespace InABox.DynamicGrid
  51. {
  52. public class TimeSpanToStringConverter : IValueConverter
  53. {
  54. public TimeSpanToStringConverter(string format)
  55. {
  56. Format = format;
  57. }
  58. public string Format { get; set; }
  59. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  60. {
  61. if (value is TimeSpan time)
  62. {
  63. var result = string.IsNullOrWhiteSpace(Format) || string.Equals(Format, "hh:mm")
  64. ? Math.Truncate(time.TotalHours).ToString("#00") + ":" + time.Minutes.ToString("D2")
  65. : string.Format("{0:" + Format.Replace(":", "\\:") + "}", time);
  66. return result;
  67. }
  68. return "";
  69. }
  70. public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  71. {
  72. return null;
  73. }
  74. }
  75. public class TimeSpanAggregate : ISummaryAggregate
  76. {
  77. public int Count { get; private set; }
  78. public TimeSpan Sum { get; private set; }
  79. public Action<IEnumerable, string, PropertyDescriptor> CalculateAggregateFunc()
  80. {
  81. return CalculateAggregate;
  82. }
  83. private void CalculateAggregate(IEnumerable items, string property, PropertyDescriptor args)
  84. {
  85. if(items is IEnumerable<DataRowView> rows)
  86. {
  87. if (string.Equals(args.Name, "Count"))
  88. {
  89. Count = rows.Count();
  90. }
  91. else if (string.Equals(args.Name, "Sum"))
  92. {
  93. Sum = new TimeSpan();
  94. foreach (var row in rows)
  95. if (row[property] is TimeSpan)
  96. Sum += (TimeSpan)row[property];
  97. }
  98. }
  99. else
  100. {
  101. Logger.Send(LogType.Error, "", $"Attempting to caluculate aggregate on invalid data type '{items.GetType()}'.");
  102. }
  103. }
  104. }
  105. public class TimeSpanAggregateRenderer : GridTableSummaryCellRenderer
  106. {
  107. public override void OnUpdateEditBinding(DataColumnBase dataColumn, GridTableSummaryCell element, object dataContext)
  108. {
  109. if (DataGrid == null)
  110. return;
  111. var record = dataContext as SummaryRecordEntry;
  112. if (record == null || record.SummaryRow == null)
  113. return;
  114. foreach (var summaryColumn in record.SummaryRow.SummaryColumns)
  115. {
  116. if (!summaryColumn.MappingName.Equals(dataColumn.GridColumn.MappingName))
  117. continue;
  118. var tsAgg = DataGrid != null
  119. ? SummaryCreator.GetSummaryAggregate(summaryColumn, DataGrid.View) as TimeSpanAggregate
  120. : null;
  121. if (tsAgg != null)
  122. {
  123. var format = summaryColumn.Format.Replace("{", "").Replace("}", "").Split(':');
  124. var cmd = format.FirstOrDefault();
  125. var fmt = format.Length > 1 ? string.Join(":", format.Skip(1)) : "";
  126. if (string.Equals(cmd, "Sum"))
  127. element.Content = string.IsNullOrWhiteSpace(fmt) || string.Equals(fmt, "hh':'mm")
  128. ? Math.Truncate(tsAgg.Sum.TotalHours).ToString("#00") + ":" + tsAgg.Sum.Minutes.ToString("D2")
  129. : string.Format("{0:" + fmt.Replace(":", "\\:") + "}", tsAgg.Sum);
  130. else if (string.Equals(summaryColumn.Format, "Count"))
  131. element.Content = string.Format(fmt, tsAgg.Count);
  132. }
  133. else
  134. {
  135. base.OnUpdateEditBinding(dataColumn, element, dataContext);
  136. }
  137. }
  138. }
  139. }
  140. public class NewDynamicGridStyle : DynamicGridStyle<VirtualizingCellsControl>
  141. {
  142. public NewDynamicGridStyle() : base(null)
  143. {
  144. }
  145. public NewDynamicGridStyle(IDynamicGridStyle source) : base(source)
  146. {
  147. }
  148. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  149. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  150. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  151. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  152. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  153. }
  154. public class GridSelectionControllerExt : GridSelectionController
  155. {
  156. public GridSelectionControllerExt(SfDataGrid datagrid)
  157. : base(datagrid)
  158. {
  159. }
  160. protected override void ProcessSelectedItemChanged(SelectionPropertyChangedHandlerArgs handle)
  161. {
  162. base.ProcessSelectedItemChanged(handle);
  163. if (handle.NewValue != null)
  164. {
  165. //this.DataGrid.ScrollInView(this.CurrentCellManager.CurrentRowColumnIndex);
  166. //int rowIndex = this.CurrentCellManager.CurrentRowColumnIndex.RowIndex;
  167. var columnIndex = CurrentCellManager.CurrentRowColumnIndex.ColumnIndex;
  168. var scrollRowIndex = DataGrid.GetVisualContainer().ScrollRows.LastBodyVisibleLineIndex;
  169. DataGrid.ScrollInView(new RowColumnIndex(scrollRowIndex, columnIndex));
  170. }
  171. }
  172. }
  173. public class DynamicGridSummaryStyleSelector : StyleSelector
  174. {
  175. private readonly IDynamicGrid _grid;
  176. public DynamicGridSummaryStyleSelector(IDynamicGrid grid)
  177. {
  178. _grid = grid;
  179. }
  180. public override Style SelectStyle(object item, DependencyObject container)
  181. {
  182. var vcol = ((GridTableSummaryCell)container).ColumnBase.ColumnIndex;
  183. var col = vcol > -1 && vcol < _grid.VisibleColumns.Count ? _grid.VisibleColumns[vcol] : null;
  184. var style = new Style(typeof(GridTableSummaryCell));
  185. style.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  186. style.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  187. style.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty,
  188. col != null ? col.HorizontalAlignment(typeof(double)) : HorizontalAlignment.Right));
  189. style.Setters.Add(new Setter(Control.BorderBrushProperty, new SolidColorBrush(Colors.Gray)));
  190. style.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0, 0, 0.75, 0)));
  191. style.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  192. style.Setters.Add(new Setter(Control.FontWeightProperty, FontWeights.DemiBold));
  193. return style;
  194. }
  195. }
  196. // Used to render boolean columns (the default "false" value shows what appears to be an intermediate state, which is ugly
  197. // This should show nothing for false, and a tick in a box for true
  198. public class BoolToImageConverter : IValueConverter
  199. {
  200. private static readonly BitmapImage tick = Resources.Bullet_Tick.AsBitmapImage();
  201. public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
  202. {
  203. return value is bool boolean && boolean ? tick : null;
  204. }
  205. public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  206. {
  207. return null;
  208. }
  209. }
  210. public class StringToColorImageConverter : IValueConverter
  211. {
  212. private readonly int _height = 50;
  213. private readonly int _width = 25;
  214. private readonly Dictionary<string, BitmapImage> cache = new();
  215. public StringToColorImageConverter(int width, int height)
  216. {
  217. _width = width;
  218. _height = height;
  219. }
  220. public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
  221. {
  222. var str = value?.ToString();
  223. if (str is null)
  224. return null;
  225. var colorcode = str.TrimStart('#');
  226. if (!cache.ContainsKey(colorcode))
  227. {
  228. var col = ImageUtils.StringToColor(colorcode);
  229. var bmp = ImageUtils.BitmapFromColor(col, _width, _height, Color.Black);
  230. cache[colorcode] = bmp.AsBitmapImage();
  231. }
  232. var result = cache[colorcode];
  233. return result;
  234. }
  235. public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  236. {
  237. return null;
  238. }
  239. }
  240. public class StringArrayConverter : IValueConverter
  241. {
  242. object? IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
  243. {
  244. if(value is string[] strArray)
  245. {
  246. return string.Join("\n", strArray);
  247. }
  248. Logger.Send(LogType.Error, "", $"Attempt to convert an object which is not a string array: {value}.");
  249. return null;
  250. }
  251. object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  252. {
  253. return value;
  254. }
  255. }
  256. public abstract class DynamicGrid<T> : BaseDynamicGrid<T> where T : BaseObject, new()
  257. {
  258. private readonly Dictionary<string, string> _filterpredicates = new();
  259. private UIElement? _header;
  260. private readonly Button Add;
  261. private bool bChanged;
  262. private bool bRefreshing;
  263. private readonly Label ClipboardSpacer;
  264. private readonly ContextMenu ColumnsMenu;
  265. private readonly Button Copy;
  266. private readonly Label Count;
  267. private readonly Button Cut;
  268. private readonly SfDataGrid DataGrid;
  269. private readonly Button Delete;
  270. private readonly DockPanel Docker;
  271. private readonly DynamicRowMovementColumn? down;
  272. private readonly Button Edit;
  273. private readonly Label EditSpacer;
  274. private readonly Button Export;
  275. private readonly Label ExportSpacer;
  276. private readonly Button DuplicateBtn;
  277. private readonly GridRowSizingOptions gridRowResizingOptions = new() { CanIncludeHiddenColumns = false, AutoFitMode = AutoFitMode.SmartFit };
  278. private readonly Button Help;
  279. private readonly Button Import;
  280. private T? inplaceeditor;
  281. private readonly Grid Layout;
  282. private readonly Label Loading;
  283. protected Dictionary<string, CoreTable> Lookups = new();
  284. private readonly Button MultiEdit;
  285. private readonly Button Paste;
  286. private readonly Button Print;
  287. private readonly Label PrintSpacer;
  288. private readonly StackPanel Stack;
  289. private readonly DynamicRowMovementColumn? up;
  290. private DataTable DataGridItems => (DataGrid.ItemsSource as DataTable)!;
  291. #region Events
  292. public event SelectItemHandler? OnSelectItem;
  293. public event OnDoubleClick? OnDoubleClick;
  294. public event OnCellDoubleClick? OnCellDoubleClick;
  295. public OnGridChanged? OnChanged;
  296. public event EditorValueChangedHandler? OnEditorValueChanged;
  297. public override event OnCustomiseEditor<T>? OnCustomiseEditor;
  298. public override event OnCustomiseColumns? OnCustomiseColumns;
  299. public override event OnFilterRecord? OnFilterRecord;
  300. #endregion
  301. public DynamicGrid() : base()
  302. {
  303. IsReady = false;
  304. Data = new CoreTable();
  305. ColumnsMenu = new ContextMenu();
  306. var SelectColumns = new MenuItem { Header = "Select Columns" };
  307. SelectColumns.Click += SelectColumnsClick;
  308. ColumnsMenu.Items.Add(SelectColumns);
  309. LoadColumnsMenu(ColumnsMenu);
  310. MasterColumns = new DynamicGridColumns();
  311. MasterColumns.ExtractColumns(typeof(T), "");
  312. foreach(var column in LookupFactory.RequiredColumns<T>().ColumnNames())
  313. {
  314. AddHiddenColumn(column);
  315. }
  316. ActionColumns = new DynamicActionColumns();
  317. if (IsSequenced)
  318. {
  319. up = new DynamicRowMovementColumn(DynamicRowMovement.Up, SwapRows);
  320. ActionColumns.Add(up);
  321. down = new DynamicRowMovementColumn(DynamicRowMovement.Down, SwapRows);
  322. ActionColumns.Add(down);
  323. HiddenColumns.Add(x => (x as ISequenceable)!.Sequence);
  324. }
  325. VisibleColumns = new DynamicGridColumns();
  326. DataGrid = new SfDataGrid();
  327. DataGrid.VerticalAlignment = VerticalAlignment.Stretch;
  328. DataGrid.HorizontalAlignment = HorizontalAlignment.Stretch;
  329. DataGrid.HeaderContextMenu = ColumnsMenu;
  330. DataGrid.CellTapped += DataGrid_CellTapped;
  331. DataGrid.CellDoubleTapped += DataGrid_CellDoubleTapped;
  332. DataGrid.SelectionMode = GridSelectionMode.Extended;
  333. DataGrid.SelectionUnit = GridSelectionUnit.Row;
  334. DataGrid.CanMaintainScrollPosition = true;
  335. DataGrid.NavigationMode = NavigationMode.Row;
  336. DataGrid.AllowEditing = false;
  337. DataGrid.EditTrigger = EditTrigger.OnTap;
  338. DataGrid.CurrentCellBeginEdit += DataGrid_CurrentCellBeginEdit;
  339. DataGrid.CurrentCellEndEdit += DataGrid_CurrentCellEndEdit;
  340. DataGrid.CurrentCellValueChanged += DataGrid_CurrentCellValueChanged;
  341. DataGrid.CurrentCellDropDownSelectionChanged += DataGrid_CurrentCellDropDownSelectionChanged;
  342. DataGrid.CurrentCellRequestNavigate += DataGrid_CurrentCellRequestNavigate;
  343. DataGrid.PreviewKeyUp += DataGrid_PreviewKeyUp;
  344. DataGrid.CurrentCellActivated += DataGrid_CurrentCellActivated;
  345. DataGrid.BorderBrush = new SolidColorBrush(Colors.Gray);
  346. DataGrid.BorderThickness = new Thickness(0.75F);
  347. DataGrid.Background = new SolidColorBrush(Colors.DimGray);
  348. DataGrid.AutoGenerateColumns = false;
  349. DataGrid.ColumnSizer = GridLengthUnitType.AutoLastColumnFill;
  350. DataGrid.SelectionForegroundBrush = BaseDynamicGrid.SelectionForeground;
  351. DataGrid.RowSelectionBrush = BaseDynamicGrid.SelectionBackground;
  352. DataGrid.CurrentCellBorderThickness = new Thickness(0);
  353. DataGrid.AllowFiltering = false;
  354. DataGrid.EnableDataVirtualization = true;
  355. DataGrid.RowHeight = 30;
  356. DataGrid.QueryRowHeight += DataGrid_QueryRowHeight;
  357. DataGrid.HeaderRowHeight = 30;
  358. DataGrid.MouseLeftButtonUp += DataGrid_MouseLeftButtonUp;
  359. DataGrid.MouseRightButtonUp += DataGrid_MouseRightButtonUp;
  360. DataGrid.KeyUp += DataGrid_KeyUp;
  361. DataGrid.PreviewGotKeyboardFocus += DataGrid_PreviewGotKeyboardFocus;
  362. //DataGrid.SelectionController = new GridSelectionControllerExt(DataGrid);
  363. DataGrid.FilterChanged += DataGrid_FilterChanged;
  364. DataGrid.FilterItemsPopulating += DataGrid_FilterItemsPopulating;
  365. var fltstyle = new Style(typeof(GridFilterControl));
  366. fltstyle.Setters.Add(new Setter(GridFilterControl.FilterModeProperty, FilterMode.Both));
  367. fltstyle.Setters.Add(new Setter(GridFilterControl.SortOptionVisibilityProperty, Visibility.Collapsed));
  368. DataGrid.FilterPopupStyle = fltstyle;
  369. DataGrid.RowStyleSelector = StyleSelector;
  370. DataGrid.TableSummaryCellStyleSelector = new DynamicGridSummaryStyleSelector(this);
  371. //DataGrid.MouseMove += DataGrid_MouseMove;
  372. DataGrid.CellToolTipOpening += DataGrid_CellToolTipOpening;
  373. //var headstyle = new Style(typeof(GridHeaderCellControl));
  374. //headstyle.Setters.Add(new Setter(GridHeaderCellControl.BackgroundProperty, new SolidColorBrush(Colors.WhiteSmoke)));
  375. //headstyle.Setters.Add(new Setter(GridHeaderCellControl.ForegroundProperty, new SolidColorBrush(Colors.Green)));
  376. //headstyle.Setters.Add(new Setter(GridHeaderCellControl.FontSizeProperty, 12.0F));
  377. //DataGrid.HeaderStyle = headstyle;
  378. DataGrid.SizeChanged += DataGrid_SizeChanged;
  379. DataGrid.SetValue(Grid.RowProperty, 1);
  380. Loading = new Label();
  381. Loading.Content = "Loading...";
  382. Loading.Foreground = new SolidColorBrush(Colors.White);
  383. Loading.VerticalContentAlignment = VerticalAlignment.Center;
  384. Loading.HorizontalContentAlignment = HorizontalAlignment.Center;
  385. Loading.Visibility = Visibility.Collapsed;
  386. Loading.SetValue(Panel.ZIndexProperty, 999);
  387. Loading.SetValue(Grid.RowProperty, 1);
  388. Loading.FontSize = 14.0F;
  389. Loading.Tag = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(50) };
  390. Help = CreateButton(Properties.Resources.help.AsBitmapImage(Color.White));
  391. Help.Margin = new Thickness(0, 2, 2, 0);
  392. Help.SetValue(DockPanel.DockProperty, Dock.Right);
  393. Help.Click += (o, e) => ShowHelp(typeof(T).Name.Split('.').Last().SplitCamelCase().Replace(" ","_"));
  394. Add = CreateButton(Properties.Resources.add.AsBitmapImage(Color.White));
  395. Add.Margin = new Thickness(0, 2, 2, 0);
  396. Add.Click += Add_Click;
  397. Edit = CreateButton(Properties.Resources.pencil.AsBitmapImage(Color.White));
  398. Edit.Margin = new Thickness(0, 2, 2, 0);
  399. Edit.Click += Edit_Click;
  400. MultiEdit = CreateButton(Properties.Resources.doc_xls.AsBitmapImage(Color.White));
  401. MultiEdit.Margin = new Thickness(0, 2, 2, 0);
  402. MultiEdit.Click += MultiEdit_Click;
  403. EditSpacer = new Label { Width = 5 };
  404. Print = CreateButton(Properties.Resources.print.AsBitmapImage(Color.White));
  405. Print.Margin = new Thickness(0, 2, 2, 0);
  406. Print.Click += (o, e) => DoPrint(o);
  407. PrintSpacer = new Label { Width = 5 };
  408. Cut = CreateButton(Properties.Resources.cut.AsBitmapImage(Color.White));
  409. Cut.Margin = new Thickness(0, 2, 2, 0);
  410. Cut.Click += Cut_Click;
  411. Copy = CreateButton(Properties.Resources.copy.AsBitmapImage(Color.White));
  412. Copy.Margin = new Thickness(0, 2, 2, 0);
  413. Copy.Click += Copy_Click;
  414. Paste = CreateButton(Properties.Resources.paste.AsBitmapImage(Color.White));
  415. Paste.Margin = new Thickness(0, 2, 2, 0);
  416. Paste.Click += Paste_Click;
  417. ClipboardSpacer = new Label { Width = 5 };
  418. Export = CreateButton(Properties.Resources.doc_xls.AsBitmapImage(Color.White), "Export");
  419. Export.Margin = new Thickness(0, 2, 2, 0);
  420. Export.Click += Export_Click;
  421. Import = CreateButton(Properties.Resources.doc_xls.AsBitmapImage(Color.White), "Import");
  422. Import.Margin = new Thickness(0, 2, 2, 0);
  423. Import.Click += Import_Click;
  424. ExportSpacer = new Label { Width = 5 };
  425. Stack = new StackPanel();
  426. Stack.Orientation = Orientation.Horizontal;
  427. Stack.SetValue(DockPanel.DockProperty, Dock.Left);
  428. Stack.Children.Add(Help);
  429. Stack.Children.Add(Add);
  430. Stack.Children.Add(Edit);
  431. Stack.Children.Add(MultiEdit);
  432. Stack.Children.Add(EditSpacer);
  433. Stack.Children.Add(Print);
  434. Stack.Children.Add(PrintSpacer);
  435. Stack.Children.Add(Cut);
  436. Stack.Children.Add(Copy);
  437. Stack.Children.Add(Paste);
  438. Stack.Children.Add(ClipboardSpacer);
  439. Stack.Children.Add(Export);
  440. Stack.Children.Add(Import);
  441. Stack.Children.Add(ExportSpacer);
  442. Delete = CreateButton(Properties.Resources.delete.AsBitmapImage(Color.White));
  443. Delete.Margin = new Thickness(0, 2, 0, 0);
  444. Delete.SetValue(DockPanel.DockProperty, Dock.Right);
  445. Delete.Click += Delete_Click;
  446. DuplicateBtn = AddButton("Duplicate", Properties.Resources.paste.AsBitmapImage(Color.White), DoDuplicate);
  447. Count = new Label();
  448. Count.Height = 30;
  449. Count.Margin = new Thickness(0, 2, 0, 0);
  450. Count.VerticalContentAlignment = VerticalAlignment.Center;
  451. Count.HorizontalContentAlignment = HorizontalAlignment.Center;
  452. Count.SetValue(DockPanel.DockProperty, Dock.Left);
  453. Docker = new DockPanel();
  454. Docker.SetValue(Grid.RowProperty, 2);
  455. Docker.SetValue(Grid.ColumnProperty, 0);
  456. Docker.Children.Add(Stack);
  457. Docker.Children.Add(Delete);
  458. Docker.Children.Add(Count);
  459. Layout = new Grid();
  460. Layout.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
  461. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  462. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
  463. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  464. Layout.Children.Add(DataGrid);
  465. Layout.Children.Add(Loading);
  466. Layout.Children.Add(Docker);
  467. //Scroll.ApplyTemplate();
  468. Content = Layout;
  469. Options.Clear();
  470. }
  471. public bool IsReady { get; private set; }
  472. public UIElement? Header
  473. {
  474. get => _header;
  475. set
  476. {
  477. if (_header is not null && Layout.Children.Contains(_header))
  478. Layout.Children.Remove(_header);
  479. _header = value;
  480. if(_header is not null)
  481. {
  482. _header.SetValue(Grid.RowProperty, 0);
  483. _header.SetValue(Grid.ColumnProperty, 0);
  484. _header.SetValue(Grid.ColumnSpanProperty, 2);
  485. Layout.Children.Add(_header);
  486. }
  487. }
  488. }
  489. /// <summary>
  490. /// Represents the data in the grid. This is <see langword="null"/> until <see cref="Refresh(bool, bool)"/> is called.
  491. /// </summary>
  492. public CoreTable? MasterData { get; set; }
  493. public DynamicActionColumns ActionColumns { get; }
  494. private bool IsSequenced => typeof(T).GetInterfaces().Any(x => x.Equals(typeof(ISequenceable)));
  495. public override double RowHeight
  496. {
  497. get => DataGrid.RowHeight;
  498. set => DataGrid.RowHeight = value;
  499. }
  500. public override double HeaderHeight
  501. {
  502. get => DataGrid.HeaderRowHeight;
  503. set => DataGrid.HeaderRowHeight = value;
  504. }
  505. protected override void OptionsChanged(object sender, EventArgs args)
  506. {
  507. ColumnsMenu.Visibility = Options.Contains(DynamicGridOption.SelectColumns) ? Visibility.Visible : Visibility.Hidden;
  508. Help.Visibility = Options.Contains(DynamicGridOption.ShowHelp) ? Visibility.Visible : Visibility.Collapsed;
  509. Add.Visibility = Options.Contains(DynamicGridOption.AddRows) ? Visibility.Visible : Visibility.Collapsed;
  510. Edit.Visibility = Options.Contains(DynamicGridOption.EditRows) ? Visibility.Visible : Visibility.Collapsed;
  511. MultiEdit.Visibility =
  512. Visibility.Collapsed; // _Options.Contains(DynamicGridOptions.DirectEdit) ? Visibility.Visible : Visibility.Collapsed;
  513. EditSpacer.Visibility = Options.Contains(DynamicGridOption.AddRows) || Options.Contains(DynamicGridOption.EditRows)
  514. ? Visibility.Visible
  515. : Visibility.Collapsed;
  516. Print.Visibility = Options.Contains(DynamicGridOption.Print) ? Visibility.Visible : Visibility.Collapsed;
  517. PrintSpacer.Visibility = Options.Contains(DynamicGridOption.Print) ? Visibility.Visible : Visibility.Collapsed;
  518. Cut.Visibility = IsSequenced ? Visibility.Visible : Visibility.Collapsed;
  519. Copy.Visibility = IsSequenced ? Visibility.Visible : Visibility.Collapsed;
  520. Paste.Visibility = IsSequenced ? Visibility.Visible : Visibility.Collapsed;
  521. ClipboardSpacer.Visibility = IsSequenced ? Visibility.Visible : Visibility.Collapsed;
  522. Export.Visibility = Options.Contains(DynamicGridOption.ExportData) ? Visibility.Visible : Visibility.Collapsed;
  523. Import.Visibility = Options.Contains(DynamicGridOption.ImportData) ? Visibility.Visible : Visibility.Collapsed;
  524. ExportSpacer.Visibility = Options.Contains(DynamicGridOption.ExportData) || Options.Contains(DynamicGridOption.ImportData)
  525. ? Visibility.Visible
  526. : Visibility.Collapsed;
  527. DataGrid.NavigationMode = Options.Contains(DynamicGridOption.DirectEdit) ? NavigationMode.Cell : NavigationMode.Row;
  528. DataGrid.AllowEditing = Options.Contains(DynamicGridOption.DirectEdit);
  529. Count.Visibility = Options.Contains(DynamicGridOption.RecordCount) ? Visibility.Visible : Visibility.Collapsed;
  530. Delete.Visibility = Options.Contains(DynamicGridOption.DeleteRows) ? Visibility.Visible : Visibility.Collapsed;
  531. DataGrid.AllowFiltering = Options.Contains(DynamicGridOption.FilterRows);
  532. DataGrid.FilterRowPosition = Options.Contains(DynamicGridOption.FilterRows) ? FilterRowPosition.FixedTop : FilterRowPosition.None;
  533. DataGrid.SelectionMode = Options.Contains(DynamicGridOption.MultiSelect) ? GridSelectionMode.Extended : GridSelectionMode.Single;
  534. if (up != null)
  535. up.Position = Options.Contains(DynamicGridOption.EditRows) ? DynamicActionColumnPosition.Start : DynamicActionColumnPosition.Hidden;
  536. if (down != null)
  537. down.Position = Options.Contains(DynamicGridOption.EditRows) ? DynamicActionColumnPosition.Start : DynamicActionColumnPosition.Hidden;
  538. if (DuplicateBtn != null)
  539. DuplicateBtn.Visibility = Visibility.Collapsed;
  540. }
  541. protected override DynamicGridStyleSelector<T> GetStyleSelector()
  542. {
  543. return new DynamicGridStyleSelector<T, NewDynamicGridStyle>();
  544. }
  545. protected override DynamicGridStyle GetStyle(CoreRow row, DynamicGridStyle style)
  546. {
  547. var result = base.GetStyle(row, style);
  548. if (ClipBuffer != null)
  549. if (ClipBuffer.Item2.Contains(row))
  550. {
  551. var bgbrush = style.Background as SolidColorBrush;
  552. var bgcolor = bgbrush != null ? bgbrush.Color : Colors.Transparent;
  553. result = new NewDynamicGridStyle(style);
  554. result.Background = ClipBuffer.Item1 == ClipAction.Cut
  555. ? new SolidColorBrush(bgcolor.MixColors(0.5, Colors.Orchid))
  556. : new SolidColorBrush(bgcolor.MixColors(0.5, Colors.LightGreen));
  557. result.Foreground = new SolidColorBrush(Colors.Gray);
  558. result.FontStyle = FontStyles.Italic;
  559. }
  560. return result;
  561. }
  562. private void DataGrid_CurrentCellActivated(object? sender, CurrentCellActivatedEventArgs e)
  563. {
  564. if (!Options.Contains(DynamicGridOption.DirectEdit))
  565. return;
  566. if (!DataGrid.SelectionController.CurrentCellManager.CurrentCell.IsEditing && e.ActivationTrigger == ActivationTrigger.Keyboard)
  567. DataGrid.SelectionController.CurrentCellManager.BeginEdit();
  568. }
  569. private void DataGrid_PreviewKeyUp(object sender, KeyEventArgs e)
  570. {
  571. if (e.Key == Key.OemPeriod)
  572. {
  573. var editor = e.OriginalSource as TimeSpanEdit;
  574. if (editor != null && editor.SelectionStart < 2) editor.SelectionStart = 3;
  575. }
  576. else if (e.Key == Key.Tab)
  577. {
  578. }
  579. //throw new NotImplementedException();
  580. }
  581. private void DataGrid_CurrentCellRequestNavigate(object? sender, CurrentCellRequestNavigateEventArgs e)
  582. {
  583. //throw new NotImplementedException();
  584. }
  585. private void DataGrid_FilterChanged(object? o, GridFilterEventArgs e)
  586. {
  587. var col = DataGrid.Columns.IndexOf(e.Column);
  588. if (ColumnList[col] is DynamicActionColumn column)
  589. {
  590. if (e.FilterPredicates != null)
  591. {
  592. var filter = e.FilterPredicates.Select(x => x.FilterValue.ToString()!).ToArray();
  593. bool include = e.FilterPredicates.Any(x => x.FilterType == FilterType.Equals);
  594. column.SelectedFilters = include ? filter : column.Filters.Except(filter).ToArray();
  595. }
  596. else
  597. column.SelectedFilters = Array.Empty<string>();
  598. DataGrid.ClearFilter(e.Column);
  599. //e.FilterPredicates?.Clear();
  600. //e.FilterPredicates?.Add(new FilterPredicate() { PredicateType = PredicateType.Or, FilterBehavior = Syncfusion.Data.FilterBehavior.StringTyped, FilterMode = ColumnFilter.DisplayText, FilterType = Syncfusion.Data.FilterType.NotEquals, FilterValue = "" });
  601. //e.FilterPredicates?.Add(new FilterPredicate() { PredicateType = PredicateType.Or, FilterBehavior = Syncfusion.Data.FilterBehavior.StringTyped, FilterMode = ColumnFilter.DisplayText, FilterType = Syncfusion.Data.FilterType.Equals, FilterValue = "" });
  602. Refresh(false, false);
  603. e.Handled = true;
  604. }
  605. if (e.FilterPredicates == null)
  606. {
  607. if (_filterpredicates.ContainsKey(e.Column.MappingName))
  608. _filterpredicates.Remove(e.Column.MappingName);
  609. }
  610. else
  611. {
  612. _filterpredicates[e.Column.MappingName] = Serialization.Serialize(e.FilterPredicates, true);
  613. }
  614. UpdateRecordCount();
  615. }
  616. private void DataGrid_FilterItemsPopulating(object? sender, GridFilterItemsPopulatingEventArgs e)
  617. {
  618. var col = DataGrid.Columns.IndexOf(e.Column);
  619. var column = ColumnList[col] as DynamicActionColumn;
  620. if (column != null)
  621. e.ItemsSource = column.Filters.Select(x => new FilterElement
  622. { DisplayText = x, ActualValue = x, IsSelected = column.SelectedFilters == null || column.SelectedFilters.Contains(x) });
  623. }
  624. private CoreRow? GetRowFromIndex(int rowIndex)
  625. {
  626. var row = rowIndex - (Options.Contains(DynamicGridOption.FilterRows) ? 2 : 1);
  627. if (row < 0)
  628. return null;
  629. row = DataGridItems.Rows.IndexOf((DataGrid.View.Records[row].Data as DataRowView)!.Row);
  630. if (row < 0)
  631. return null;
  632. return Data.Rows[row];
  633. }
  634. private void DataGrid_CellToolTipOpening(object? sender, GridCellToolTipOpeningEventArgs e)
  635. {
  636. if (ColumnList[e.RowColumnIndex.ColumnIndex] is not DynamicActionColumn col)
  637. return;
  638. var toolTip = col.ToolTip;
  639. if (toolTip is null)
  640. return;
  641. var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
  642. if (row is null)
  643. return;
  644. e.ToolTip.Template = TemplateGenerator.CreateControlTemplate(
  645. typeof(ToolTip),
  646. () => toolTip.Invoke(col, row)
  647. );
  648. }
  649. //private void DataGrid_MouseMove(object sender, MouseEventArgs e)
  650. //{
  651. // var visualcontainer = DataGrid.GetVisualContainer();
  652. // var point = e.GetPosition(visualcontainer);
  653. // var rowColumnIndex = visualcontainer.PointToCellRowColumnIndex(point);
  654. // var recordIndex = DataGrid.ResolveToRecordIndex(rowColumnIndex.RowIndex);
  655. // if (recordIndex < 0)
  656. // return;
  657. // if (!rowColumnIndex.IsEmpty)
  658. // {
  659. // if (DataGrid.View.TopLevelGroup != null)
  660. // {
  661. // // Get the current row record while grouping
  662. // var record = DataGrid.View.TopLevelGroup.DisplayElements[recordIndex];
  663. // if (record.GetType() == typeof(RecordEntry))
  664. // {
  665. // var data = (record as RecordEntry).Data as CoreRow;
  666. // }
  667. // }
  668. // else
  669. // {
  670. // //For getting the record, need to resolve the corresponding record index from row index                     
  671. // var record1 = DataGrid.View.Records[DataGrid.ResolveToRecordIndex(rowColumnIndex.RowIndex)].Data;
  672. // }
  673. // //Gets the column from ColumnsCollection by resolving the corresponding column index from  GridVisibleColumnIndex                      
  674. // var gridColumn = DataGrid.Columns[DataGrid.ResolveToGridVisibleColumnIndex(rowColumnIndex.ColumnIndex)];
  675. // if (gridColumn is GridImageColumn)
  676. // {
  677. // }
  678. // }
  679. //}
  680. protected virtual void LoadColumnsMenu(ContextMenu menu)
  681. {
  682. }
  683. private void DataGrid_CurrentCellBeginEdit(object? sender, CurrentCellBeginEditEventArgs e)
  684. {
  685. var headerrows = Options.Contains(DynamicGridOption.FilterRows) ? 2 : 1;
  686. if (e.RowColumnIndex.RowIndex < headerrows)
  687. return;
  688. if (inplaceeditor == null)
  689. inplaceeditor = LoadItem(Data.Rows[e.RowColumnIndex.RowIndex - headerrows]);
  690. var column = DataGrid.Columns[e.RowColumnIndex.ColumnIndex] as GridComboBoxColumn;
  691. if (column != null && column.ItemsSource == null)
  692. {
  693. var colname = column.MappingName;
  694. var colno = DataGridItems.Columns.IndexOf(colname);
  695. var property = Data.Columns[colno].ColumnName;
  696. var prop = CoreUtils.GetProperty(typeof(T), property);
  697. var editor = prop.GetEditor();
  698. if (editor is ILookupEditor)
  699. {
  700. if (!Lookups.ContainsKey(property))
  701. Lookups[property] = ((ILookupEditor)editor).Values(property);
  702. var combo = column;
  703. combo.ItemsSource = Lookups[property].ToDictionary(Lookups[property].Columns[0].ColumnName, "Display");
  704. combo.SelectedValuePath = "Key";
  705. combo.DisplayMemberPath = "Value";
  706. }
  707. }
  708. bChanged = false;
  709. }
  710. private void DataGrid_CurrentCellValueChanged(object? sender, CurrentCellValueChangedEventArgs e)
  711. {
  712. var headerrows = Options.Contains(DynamicGridOption.FilterRows) ? 2 : 1;
  713. if (e.RowColumnIndex.RowIndex < headerrows)
  714. return;
  715. if (e.Column is GridCheckBoxColumn)
  716. inplaceeditor = LoadItem(Data.Rows[e.RowColumnIndex.RowIndex - headerrows]);
  717. if(inplaceeditor is not null)
  718. UpdateData(inplaceeditor, e.RowColumnIndex.ColumnIndex);
  719. if (e.Column is GridCheckBoxColumn)
  720. inplaceeditor = null;
  721. if (inplaceeditor is not null)
  722. bChanged = true;
  723. }
  724. private void DataGrid_CurrentCellDropDownSelectionChanged(object? sender, CurrentCellDropDownSelectionChangedEventArgs e)
  725. {
  726. var headerrows = Options.Contains(DynamicGridOption.FilterRows) ? 2 : 1;
  727. if (e.RowColumnIndex.RowIndex < headerrows)
  728. return;
  729. inplaceeditor ??= LoadItem(Data.Rows[e.RowColumnIndex.RowIndex - headerrows]);
  730. if (inplaceeditor != null)
  731. bChanged = true;
  732. }
  733. protected void UpdateCell(int row, string colname, object value)
  734. {
  735. var table = DataGridItems;
  736. var colno = table.Columns.IndexOf(colname);
  737. var corecol = Data.Columns[colno].ColumnName;
  738. var corerow = Data.Rows[row];
  739. corerow[corecol] = value;
  740. var datarow = table.Rows[row];
  741. datarow[colname] = value;
  742. }
  743. private void DataGrid_CurrentCellEndEdit(object? sender, CurrentCellEndEditEventArgs e)
  744. {
  745. var headerrows = Options.Contains(DynamicGridOption.FilterRows) ? 2 : 1;
  746. if (e.RowColumnIndex.RowIndex < headerrows)
  747. return;
  748. if (inplaceeditor is not null && bChanged) UpdateData(inplaceeditor, e.RowColumnIndex.ColumnIndex);
  749. bChanged = false;
  750. inplaceeditor = null;
  751. }
  752. private void UpdateData(T obj, int columnindex)
  753. {
  754. var table = DataGridItems;
  755. var iRow = SelectedRows.First().Index; //e.RowColumnIndex.RowIndex - (Options.Contains(DynamicGridOptions.FilterRows) ? 2 : 1);
  756. var row = table.Rows[iRow];
  757. var colname = DataGrid.Columns[columnindex].MappingName;
  758. var value = row[colname];
  759. var colno = table.Columns.IndexOf(colname);
  760. var corecol = Data.Columns[colno].ColumnName;
  761. var corerow = Data.Rows[iRow];
  762. corerow[corecol] = value;
  763. CoreUtils.SetPropertyValue(obj, corecol, value);
  764. SaveItem(obj);
  765. Data.LoadRow(corerow, obj);
  766. foreach (var column in Data.Columns.Where(x => !string.Equals(corecol, x.ColumnName)))
  767. {
  768. var scol = column.ColumnName.Replace('.', '_');
  769. row[scol] = corerow[column.ColumnName];
  770. }
  771. for (var i = 0; i < ActionColumns.Count; i++) row[string.Format("ActionColumn{0}", i)] = ActionColumns[i].Image.Invoke(corerow);
  772. }
  773. private void DataGrid_QueryRowHeight(object? sender, QueryRowHeightEventArgs e)
  774. {
  775. if (e.RowIndex > 0)
  776. {
  777. e.Height = DataGrid.RowHeight;
  778. if (DataGrid.GridColumnSizer.GetAutoRowHeight(e.RowIndex, gridRowResizingOptions, out var autoHeight))
  779. if (autoHeight > DataGrid.RowHeight)
  780. e.Height = autoHeight;
  781. e.Handled = true;
  782. }
  783. }
  784. private void DataGrid_SizeChanged(object sender, SizeChangedEventArgs e)
  785. {
  786. if (IsReady && !bRefreshing) ResizeColumns(DataGrid, e.NewSize.Width - 2, e.NewSize.Height - 2);
  787. }
  788. #region Row Selections
  789. protected CoreRow[] GetVisibleRows()
  790. {
  791. var items = DataGrid.ItemsSource;
  792. var result = new List<CoreRow>();
  793. var table = DataGridItems;
  794. var rows = DataGrid.View.Records.Select(x => (x.Data as DataRowView)!).ToList();
  795. foreach (var row in rows)
  796. {
  797. var iRow = table.Rows.IndexOf(row.Row);
  798. result.Add(Data.Rows[iRow]);
  799. }
  800. //foreach (var item in DataGrid.SelectedItems)
  801. //{
  802. // if (item is CoreRow)
  803. // {
  804. // //result.Add(item as CoreRow);
  805. // }
  806. // else
  807. // {
  808. // var datarow = item as System.Data.DataRowView;
  809. // int row = datarow.Row.Table.Rows.IndexOf(datarow.Row);
  810. // result.Add(Data.Rows[row]);
  811. // }
  812. //}
  813. return result.ToArray();
  814. }
  815. private CoreRow[] GetSelectedRows()
  816. {
  817. //Logger.Send(LogType.Information, ClientFactory.UserID, String.Format("{0}: GetSelectedRows({1})", this.GetType().EntityName(), DataGrid.SelectedItems.Count));
  818. var result = new List<CoreRow>();
  819. foreach (var item in DataGrid.SelectedItems)
  820. if (item is CoreRow)
  821. {
  822. //result.Add(item as CoreRow);
  823. }
  824. else
  825. {
  826. var datarow = item as DataRowView;
  827. if (datarow != null)
  828. {
  829. var row = datarow.Row.Table.Rows.IndexOf(datarow.Row);
  830. result.Add(Data.Rows[row]);
  831. }
  832. }
  833. return result.ToArray();
  834. }
  835. private void SetSelectedRows(CoreRow[] rows)
  836. {
  837. //Logger.Send(LogType.Information, ClientFactory.UserID, String.Format("{0}: SetSelectedRows({1})", this.GetType().EntityName(), rows.Length));
  838. // CoreTableAdapter<T> adapter = (CoreTableAdapter<T>)DataGrid.ItemsSource;
  839. DataGrid.SelectedItems.Clear();
  840. var bFirst = true;
  841. foreach (var row in rows.Where(x => x.Index > -1))
  842. {
  843. //DataTable table = (DataTable)DataGrid.ItemsSource;
  844. if (bFirst || Options.Contains(DynamicGridOption.MultiSelect))
  845. DataGrid.SelectedItems.Add(DataGrid.GetRecordAtRowIndex(row.Index + (Options.Contains(DynamicGridOption.FilterRows) ? 2 : 1)));
  846. bFirst = false;
  847. }
  848. }
  849. public override CoreRow[] SelectedRows
  850. {
  851. get => GetSelectedRows();
  852. set => SetSelectedRows(value);
  853. }
  854. protected virtual void SelectItems(CoreRow[]? rows)
  855. {
  856. OnSelectItem?.Invoke(this, new DynamicGridSelectionEventArgs(rows));
  857. DuplicateBtn.Visibility =
  858. typeof(T).IsAssignableTo(typeof(IDuplicatable)) && rows != null && rows.Length >= 1 ? Visibility.Visible : Visibility.Collapsed;
  859. }
  860. private bool bFilterVisible;
  861. private bool bSwallowKey;
  862. private void DataGrid_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
  863. {
  864. var bOld = bFilterVisible;
  865. if (e.NewFocus is GridFilterControl)
  866. bFilterVisible = true;
  867. else if (e.NewFocus is ScrollViewer || e.NewFocus is SfDataGrid)
  868. bFilterVisible = false;
  869. if (bOld && !bFilterVisible)
  870. {
  871. //Logger.Send(LogType.Information, "", String.Format("{0}: PreviewGotKeyboardFocus -> {1}", this.GetType().EntityName(), e.NewFocus.GetType().EntityName()));
  872. SelectItems(SelectedRows);
  873. bSwallowKey = true;
  874. }
  875. }
  876. private void DataGrid_KeyUp(object sender, KeyEventArgs e)
  877. {
  878. if (!bFilterVisible && !bSwallowKey && DataGrid.SelectedIndex > -1)
  879. //Logger.Send(LogType.Information, "", String.Format("{0}: KeyUp -> {1}", this.GetType().EntityName(), SelectedRows.Length));
  880. SelectItems(SelectedRows);
  881. bSwallowKey = false;
  882. if (IsSequenced)
  883. {
  884. if (e.Key == Key.X && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  885. {
  886. CutToClipBuffer();
  887. }
  888. else if (e.Key == Key.C && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  889. {
  890. CopyToClipBuffer();
  891. }
  892. else if (e.Key == Key.V && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  893. {
  894. PasteFromClipBuffer();
  895. }
  896. else if (e.Key == Key.Escape)
  897. {
  898. ResetClipBuffer();
  899. InvalidateGrid();
  900. }
  901. }
  902. }
  903. private DispatcherTimer? clicktimer;
  904. private void StartTimer()
  905. {
  906. if (clicktimer is null)
  907. {
  908. clicktimer = new DispatcherTimer();
  909. clicktimer.Interval = TimeSpan.FromMilliseconds(200);
  910. clicktimer.Tick += (o, e) =>
  911. {
  912. clicktimer.IsEnabled = false;
  913. SelectItems(SelectedRows);
  914. };
  915. }
  916. clicktimer.IsEnabled = true;
  917. }
  918. private void StopTimer()
  919. {
  920. if (clicktimer is not null)
  921. clicktimer.IsEnabled = false;
  922. }
  923. private void DataGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
  924. {
  925. if (!IsEnabled)
  926. return;
  927. var visualContainer = DataGrid.GetVisualContainer();
  928. var rowcolumnindex = visualContainer.PointToCellRowColumnIndex(e.GetPosition(visualContainer));
  929. var columnindex = DataGrid.ResolveToGridVisibleColumnIndex(rowcolumnindex.ColumnIndex);
  930. var column = ColumnList[columnindex] as DynamicActionColumn;
  931. var rowindex = rowcolumnindex.RowIndex - (Options.Contains(DynamicGridOption.FilterRows) ? 2 : 1);
  932. if (rowindex < 0)
  933. return;
  934. var row = Data.Rows[rowindex];
  935. var menu = column?.ContextMenu?.Invoke(SelectedRows);
  936. if (menu != null && menu.Items.Count > 0)
  937. menu.IsOpen = true;
  938. }
  939. private void DataGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
  940. {
  941. if (!IsEnabled)
  942. return;
  943. // Header Click Here!
  944. if (DataGrid.SelectedIndex == -1)
  945. {
  946. var visualContainer = DataGrid.GetVisualContainer();
  947. var rowcolumnindex = visualContainer.PointToCellRowColumnIndex(e.GetPosition(visualContainer));
  948. var columnindex = DataGrid.ResolveToGridVisibleColumnIndex(rowcolumnindex.ColumnIndex);
  949. if (columnindex > -1 && columnindex < ColumnList.Count)
  950. {
  951. var bRefresh = false;
  952. var dac = ColumnList[columnindex] as DynamicActionColumn;
  953. if (dac != null)
  954. if (dac.Action?.Invoke(null) == true)
  955. bRefresh = true;
  956. if (bRefresh)
  957. Dispatcher.Invoke(() => { Refresh(false, true); });
  958. }
  959. }
  960. else if (!bFilterVisible)
  961. {
  962. StartTimer();
  963. }
  964. bSwallowKey = false;
  965. }
  966. private void DataGrid_CellTapped(object? sender, GridCellTappedEventArgs e)
  967. {
  968. if (!IsEnabled)
  969. return;
  970. var dac = ColumnList[e.RowColumnIndex.ColumnIndex] as DynamicActionColumn;
  971. if (dac != null)
  972. {
  973. var bRefresh = false;
  974. {
  975. foreach (var row in SelectedRows)
  976. if (dac.Action?.Invoke(row) == true)
  977. bRefresh = true;
  978. }
  979. if (bRefresh)
  980. Task.Run(() => { Dispatcher.Invoke(() => { Refresh(false, true); }); });
  981. }
  982. else
  983. {
  984. StartTimer();
  985. }
  986. }
  987. protected virtual void DoDoubleClick(object sender)
  988. {
  989. if (Options.Contains(DynamicGridOption.DirectEdit))
  990. return;
  991. SelectItems(SelectedRows);
  992. var args = new HandledEventArgs(false);
  993. OnDoubleClick?.Invoke(sender, args);
  994. if (args.Handled)
  995. return;
  996. if (Options.Contains(DynamicGridOption.EditRows))
  997. DoEdit();
  998. }
  999. private void DataGrid_CellDoubleTapped(object? sender, GridCellDoubleTappedEventArgs e)
  1000. {
  1001. StopTimer();
  1002. if(OnCellDoubleClick is not null && ColumnList[e.RowColumnIndex.ColumnIndex] is DynamicGridColumn column)
  1003. {
  1004. var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
  1005. var args = new DynamicGridCellClickEventArgs(row, column);
  1006. OnCellDoubleClick?.Invoke(this, args);
  1007. if (args.Handled)
  1008. return;
  1009. }
  1010. if (e.Record != null)
  1011. DoDoubleClick(this);
  1012. }
  1013. #endregion
  1014. #region Column Handling
  1015. private readonly List<DynamicColumnBase> ColumnList = new();
  1016. protected virtual DynamicGridColumns LoadColumns()
  1017. {
  1018. var result = new DynamicGridColumns();
  1019. var cols = Options.Contains(DynamicGridOption.DirectEdit)
  1020. ? new Columns<T>().Default(ColumnType.IncludeForeignKeys)
  1021. : new Columns<T>().Default(ColumnType.IncludeLinked);
  1022. result.AddRange(MasterColumns.Where(x => cols.Items.Any(c => c.Property.Equals(x.ColumnName)))
  1023. .OrderBy(x => CoreUtils.GetPropertySequence(typeof(T), x.ColumnName)));
  1024. return result;
  1025. }
  1026. private bool SwapRows(int row1, int row2)
  1027. {
  1028. CoreRow[] rows = Data.Rows.Where(x => x.Index.Equals(row1) || x.Index.Equals(row2)).ToArray();
  1029. var items = LoadItems(rows);
  1030. var first = (items.First() as ISequenceable)!;
  1031. var last = (items.Last() as ISequenceable)!;
  1032. var iBuf1 = first.Sequence;
  1033. var iBuf2 = last.Sequence;
  1034. first.Sequence = iBuf2;
  1035. last.Sequence = iBuf1;
  1036. SaveItems(items);
  1037. return true;
  1038. }
  1039. protected virtual void SaveColumns(DynamicGridColumns columns)
  1040. {
  1041. }
  1042. public override int DesiredWidth()
  1043. {
  1044. var result = 0;
  1045. for (var i = 0; i < ColumnList.Count; i++)
  1046. {
  1047. var col = ColumnList[i];
  1048. if (col is DynamicActionColumn)
  1049. {
  1050. result += (int)RowHeight;
  1051. }
  1052. else if (col is DynamicGridColumn)
  1053. {
  1054. var dgc = (DynamicGridColumn)col;
  1055. result += dgc.Width > 0 ? dgc.Width : 300;
  1056. }
  1057. }
  1058. return result;
  1059. }
  1060. private void ResizeColumns(SfDataGrid grid, double width, double height)
  1061. {
  1062. if (Data == null || width <= 0)
  1063. return;
  1064. var fAvailWidth = width;
  1065. //if (Data.Rows.Count * (DataGrid.RowHeight + 1) + DataGrid.HeaderRowHeight > height + 0.5F)
  1066. if(height < DataGrid.AutoScroller.VScrollBar.Maximum)
  1067. fAvailWidth -= (SystemParameters.VerticalScrollBarWidth+0.75);
  1068. double fCurWidth = 0.0F;
  1069. var NumAutoCols = 0;
  1070. var colWidths = new Dictionary<int, double>();
  1071. for (var i = 0; i < ColumnList.Count; i++)
  1072. {
  1073. var col = ColumnList[i];
  1074. if (col is DynamicActionColumn dac)
  1075. {
  1076. colWidths[i] = dac.Width == 0 ? RowHeight : dac.Width;
  1077. fCurWidth += colWidths[i];
  1078. }
  1079. else if (col is DynamicGridColumn dgc)
  1080. {
  1081. colWidths[i] = dgc.Width;
  1082. if (dgc.Width != 0)
  1083. fCurWidth += Math.Max(0.0F, dgc.Width);
  1084. else
  1085. NumAutoCols++;
  1086. }
  1087. }
  1088. if (NumAutoCols > 0)
  1089. {
  1090. var fAutoWidth = (fAvailWidth - fCurWidth) / NumAutoCols;
  1091. if (fAutoWidth < 100)
  1092. fAutoWidth = 100;
  1093. for (var i = 0; i < ColumnList.Count; i++)
  1094. if (colWidths[i] == 0)
  1095. colWidths[i] = fAutoWidth;
  1096. }
  1097. foreach (var index in colWidths.Keys)
  1098. DataGrid.Columns[index].Width = Math.Max(0.0F, colWidths[index]);
  1099. var vc = DataGrid.GetVisualContainer();
  1100. vc.RowHeightManager.Reset();
  1101. vc.InvalidateMeasureInfo();
  1102. if (vc.ScrollOwner != null)
  1103. vc.ScrollOwner.HorizontalScrollBarVisibility = vc.ExtentWidth <= fAvailWidth ? ScrollBarVisibility.Hidden : ScrollBarVisibility.Visible;
  1104. }
  1105. private void LoadActionColumns(DynamicActionColumnPosition position)
  1106. {
  1107. for (var i = 0; i < ActionColumns.Count; i++)
  1108. {
  1109. var column = ActionColumns[i];
  1110. if (column.Position == position)
  1111. {
  1112. //String sColName = String.Format("ActionColumn{0}{1}", i, position == DynamicActionColumnPosition.Start ? "L" : "R");
  1113. var sColName = string.Format("ActionColumn{0}", i);
  1114. gridRowResizingOptions.ExcludeColumns.Add(sColName);
  1115. var newcol = new GridImageColumn();
  1116. newcol.MappingName = sColName;
  1117. //newcol.Stretch = Stretch.Uniform;
  1118. newcol.Width = column.Width == 0 ? DataGrid.RowHeight : column.Width;
  1119. newcol.Padding = new Thickness(4);
  1120. newcol.ImageHeight = DataGrid.RowHeight - 8;
  1121. newcol.ImageWidth = DataGrid.RowHeight - 8;
  1122. newcol.ColumnSizer = GridLengthUnitType.None;
  1123. newcol.HeaderText = column.HeaderText;
  1124. newcol.AllowFiltering = column.Filters != null && column.Filters.Any();
  1125. newcol.AllowSorting = false;
  1126. newcol.FilterRowOptionsVisibility = Visibility.Collapsed;
  1127. newcol.ShowToolTip = column.ToolTip != null;
  1128. var style = new Style();
  1129. style.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  1130. style.Setters.Add(new Setter(IsEnabledProperty, false));
  1131. newcol.FilterRowCellStyle = style;
  1132. var headstyle = new Style(typeof(GridHeaderCellControl));
  1133. headstyle.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  1134. headstyle.Setters.Add(new Setter(ForegroundProperty, new SolidColorBrush(Colors.Black)));
  1135. headstyle.Setters.Add(new Setter(FontSizeProperty, 12D));
  1136. if (!string.IsNullOrWhiteSpace(column.HeaderText))
  1137. {
  1138. //headstyle.Setters.Add(new Setter(LayoutTransformProperty, new RotateTransform(270.0F)));
  1139. headstyle.Setters.Add(new Setter(BorderThicknessProperty, new Thickness(0.0, 0.0, 0, 0)));
  1140. headstyle.Setters.Add(new Setter(MarginProperty, new Thickness(0, 0, 0.75, 0.75)));
  1141. headstyle.Setters.Add(new Setter(TemplateProperty, Application.Current.Resources["VerticalColumnHeader"] as ControlTemplate));
  1142. }
  1143. else
  1144. {
  1145. var image = column.Image?.Invoke(null);
  1146. if (image != null)
  1147. {
  1148. var template = new ControlTemplate(typeof(GridHeaderCellControl));
  1149. var border = new FrameworkElementFactory(typeof(Border));
  1150. border.SetValue(Border.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro));
  1151. border.SetValue(Border.PaddingProperty, new Thickness(4));
  1152. border.SetValue(MarginProperty, new Thickness(0, 0, 1, 1));
  1153. var img = new FrameworkElementFactory(typeof(Image));
  1154. img.SetValue(Image.SourceProperty, image);
  1155. border.AppendChild(img);
  1156. template.VisualTree = border;
  1157. headstyle.Setters.Add(new Setter(TemplateProperty, template));
  1158. }
  1159. }
  1160. newcol.HeaderStyle = headstyle;
  1161. DataGrid.Columns.Add(newcol);
  1162. ColumnList.Add(column);
  1163. }
  1164. }
  1165. }
  1166. private bool CanSort()
  1167. {
  1168. return !IsSequenced;
  1169. }
  1170. private void ReloadColumns()
  1171. {
  1172. ConfigureColumns(MasterColumns /*, false */);
  1173. VisibleColumns = LoadColumns();
  1174. ConfigureColumns(VisibleColumns /*, true */);
  1175. DataGrid.Columns.Suspend();
  1176. ColumnList.Clear();
  1177. DataGrid.Columns.Clear();
  1178. DataGrid.TableSummaryRows.Clear();
  1179. var Summaries = new ObservableCollection<ISummaryColumn>();
  1180. gridRowResizingOptions.ExcludeColumns = new List<string>();
  1181. LoadActionColumns(DynamicActionColumnPosition.Start);
  1182. foreach (var column in VisibleColumns)
  1183. {
  1184. var filtering = true;
  1185. IProperty? prop;
  1186. try
  1187. {
  1188. prop = DatabaseSchema.Property(typeof(T), column.ColumnName);
  1189. }
  1190. catch (Exception e)
  1191. {
  1192. Logger.Send(LogType.Error, ClientFactory.UserID,
  1193. string.Format("Error constructing Column [{0}] : {1}\n{2}", column.ColumnName, e.Message, e.StackTrace));
  1194. prop = null;
  1195. }
  1196. if (prop != null)
  1197. {
  1198. var scolname = column.ColumnName.Replace('.', '_');
  1199. GridColumn newcol;
  1200. if (prop.PropertyType.IsNumeric())
  1201. {
  1202. var digits = 0;
  1203. var prefix = "N";
  1204. if (column.Editor is CurrencyEditor currencyEditor)
  1205. {
  1206. var curcol = new GridCurrencyColumn();
  1207. if (!prop.PropertyType.IsOrdinal())
  1208. {
  1209. var format = string.IsNullOrWhiteSpace(column.Format) ? "" : column.Format.Replace("C", "");
  1210. if (!int.TryParse(format, out digits))
  1211. digits = currencyEditor.Digits;
  1212. }
  1213. curcol.CurrencyDecimalDigits = digits;
  1214. curcol.CurrencyGroupSeparator = ",";
  1215. curcol.CurrencyGroupSizes = new Int32Collection(new[] { 3, 3, 3, 3, 3, 3 });
  1216. prefix = "C";
  1217. newcol = curcol;
  1218. }
  1219. else
  1220. {
  1221. var numcol = new GridNumericColumn();
  1222. if (!prop.PropertyType.IsOrdinal())
  1223. {
  1224. var format = string.IsNullOrWhiteSpace(column.Format) ? "" : column.Format.Replace("F", "");
  1225. if (!int.TryParse(format, out digits))
  1226. digits = column.Editor is DoubleEditor doubleEditor ? doubleEditor.Digits : 0;
  1227. numcol.NumberDecimalDigits = digits;
  1228. numcol.NumberGroupSeparator = ",";
  1229. numcol.NumberGroupSizes = new Int32Collection(new[] { 3, 3, 3, 3, 3, 3 });
  1230. }
  1231. else
  1232. {
  1233. numcol.NumberGroupSeparator = "";
  1234. numcol.NumberDecimalDigits = 0;
  1235. }
  1236. prefix = "N";
  1237. newcol = numcol;
  1238. }
  1239. if (prop.Editor.Summary != Summary.None)
  1240. {
  1241. var summary = new GridSummaryColumn
  1242. {
  1243. Name = scolname,
  1244. Format = "{" + (prop.Editor.Summary == Summary.Sum ? "Sum" : "Count") + ":" +
  1245. string.Format("{0}{1}", prefix, digits) +
  1246. "}",
  1247. MappingName = scolname,
  1248. SummaryType = prop.Editor.Summary == Summary.Sum
  1249. ? prop.PropertyType.IsOrdinal() ? SummaryType.Int32Aggregate : SummaryType.DoubleAggregate
  1250. : SummaryType.CountAggregate
  1251. };
  1252. Summaries.Add(summary);
  1253. }
  1254. }
  1255. else if (prop.PropertyType == typeof(DateTime))
  1256. {
  1257. newcol = new GridDateTimeColumn
  1258. {
  1259. CustomPattern = column.Format,
  1260. Pattern = !string.IsNullOrWhiteSpace(column.Format) ? DateTimePattern.CustomPattern : DateTimePattern.ShortDate
  1261. };
  1262. }
  1263. else if (prop.PropertyType == typeof(TimeSpan))
  1264. {
  1265. newcol = new GridTimeSpanColumn
  1266. {
  1267. DisplayBinding = new Binding
  1268. {
  1269. Path = new PropertyPath(scolname),
  1270. Converter = new TimeSpanToStringConverter(column.Format)
  1271. },
  1272. Format = column.Format, //.Replace(":", "':'"),
  1273. ShowArrowButtons = false
  1274. };
  1275. filtering = false;
  1276. if (prop.Editor != null && prop.Editor.Summary != Summary.None)
  1277. {
  1278. var summary = new GridSummaryColumn
  1279. {
  1280. Name = scolname,
  1281. Format = "{" + (prop.Editor.Summary == Summary.Sum
  1282. ? "Sum" + (string.IsNullOrWhiteSpace(column.Format) ? "" : ":" + column.Format.Replace(":", "':'"))
  1283. : prop.Editor.Summary == Summary.Count
  1284. ? "Count"
  1285. : "") + "}",
  1286. MappingName = scolname,
  1287. SummaryType = prop.Editor.Summary == Summary.Sum ? SummaryType.Custom : SummaryType.CountAggregate,
  1288. CustomAggregate = new TimeSpanAggregate()
  1289. };
  1290. Summaries.Add(summary);
  1291. }
  1292. }
  1293. else if (prop.PropertyType == typeof(bool))
  1294. {
  1295. if (Options.Contains(DynamicGridOption.DirectEdit))
  1296. {
  1297. var checkcol = new GridCheckBoxColumn
  1298. {
  1299. ValueBinding = new Binding
  1300. {
  1301. Path = new PropertyPath(scolname)
  1302. },
  1303. IsThreeState = false
  1304. };
  1305. newcol = checkcol;
  1306. }
  1307. else
  1308. {
  1309. var imgcol = new GridImageColumn
  1310. {
  1311. ValueBinding = new Binding
  1312. {
  1313. Path = new PropertyPath(scolname),
  1314. Converter = new BoolToImageConverter()
  1315. },
  1316. ImageHeight = DataGrid.RowHeight - 8,
  1317. ImageWidth = DataGrid.RowHeight - 8,
  1318. Padding = new Thickness(4)
  1319. };
  1320. newcol = imgcol;
  1321. }
  1322. gridRowResizingOptions.ExcludeColumns.Add(scolname);
  1323. filtering = false;
  1324. }
  1325. else if (prop.Editor is ColorEditor)
  1326. {
  1327. var imgcol = new GridImageColumn
  1328. {
  1329. ValueBinding = new Binding
  1330. {
  1331. Path = new PropertyPath(scolname),
  1332. Converter = new StringToColorImageConverter(column.Width - 8, (int)DataGrid.RowHeight - 8)
  1333. },
  1334. ImageHeight = DataGrid.RowHeight - 8,
  1335. ImageWidth = column.Width - 8,
  1336. Padding = new Thickness(4)
  1337. };
  1338. gridRowResizingOptions.ExcludeColumns.Add(scolname);
  1339. newcol = imgcol;
  1340. filtering = false;
  1341. }
  1342. else if (prop.Editor is ILookupEditor lookupEditor)
  1343. {
  1344. var lookupcol = new GridComboBoxColumn();
  1345. //var lookups = editor.Values(column.ColumnName).ToDictionary(column.ColumnName, "Display");
  1346. //lookupcol.SelectedValuePath = "Key";
  1347. //lookupcol.DisplayMemberPath = "Value";
  1348. //lookupcol.ItemsSource = lookups;
  1349. var table = lookupEditor.Values(column.ColumnName).ToDataTable();
  1350. lookupcol.SelectedValuePath = table.Columns[0].ColumnName;
  1351. lookupcol.DisplayMemberPath = "Display";
  1352. lookupcol.ItemsSource = table.DefaultView;
  1353. newcol = lookupcol;
  1354. }
  1355. else
  1356. {
  1357. var textcol = new GridTextColumn();
  1358. if (!(prop.Editor is MemoEditor))
  1359. gridRowResizingOptions.ExcludeColumns.Add(scolname);
  1360. textcol.TextWrapping = TextWrapping.NoWrap;
  1361. newcol = textcol;
  1362. if (prop.PropertyType == typeof(string[]))
  1363. newcol.DisplayBinding = new Binding { Path = new PropertyPath(scolname), Converter = new StringArrayConverter() };
  1364. textcol.AllowEditing = Options.Contains(DynamicGridOption.DirectEdit);
  1365. textcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
  1366. }
  1367. DataGrid.SummaryCalculationUnit = SummaryCalculationUnit.AllRows;
  1368. DataGrid.LiveDataUpdateMode = LiveDataUpdateMode.AllowSummaryUpdate;
  1369. newcol.MappingName = scolname;
  1370. newcol.Width = column.Width; // != 0 ? column.Width : double.NaN;
  1371. newcol.ColumnSizer =
  1372. GridLengthUnitType.None; //column.Width != 0 ? GridLengthUnitType.None : GridLengthUnitType.AutoWithLastColumnFill;
  1373. newcol.HeaderText = string.IsNullOrWhiteSpace(column.Caption) ? column.ColumnName : column.Caption;
  1374. newcol.TextAlignment = column.Alignment == Alignment.NotSet
  1375. ? prop.PropertyType.IsNumeric() ? TextAlignment.Right : TextAlignment.Left
  1376. : column.Alignment == Alignment.BottomLeft || column.Alignment == Alignment.MiddleLeft ||
  1377. column.Alignment == Alignment.TopLeft
  1378. ? TextAlignment.Left
  1379. : column.Alignment == Alignment.BottomCenter || column.Alignment == Alignment.MiddleCenter ||
  1380. column.Alignment == Alignment.TopCenter
  1381. ? TextAlignment.Center
  1382. : TextAlignment.Right;
  1383. newcol.HorizontalHeaderContentAlignment = newcol.TextAlignment == TextAlignment.Left ? HorizontalAlignment.Left
  1384. : newcol.TextAlignment == TextAlignment.Center ? HorizontalAlignment.Center
  1385. : HorizontalAlignment.Right;
  1386. var filterstyle = new Style();
  1387. if (filtering)
  1388. {
  1389. filterstyle.Setters.Add(new Setter(BackgroundProperty, BaseDynamicGrid.FilterBackground));
  1390. newcol.ImmediateUpdateColumnFilter = true;
  1391. newcol.ColumnFilter = ColumnFilter.Value;
  1392. newcol.FilterRowCondition = FilterRowCondition.Contains;
  1393. newcol.FilterRowOptionsVisibility = Visibility.Collapsed;
  1394. newcol.AllowBlankFilters = true;
  1395. newcol.AllowSorting = CanSort();
  1396. }
  1397. else
  1398. {
  1399. filterstyle.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  1400. filterstyle.Setters.Add(new Setter(IsEnabledProperty, false));
  1401. newcol.ColumnFilter = ColumnFilter.Value;
  1402. newcol.AllowFiltering = false;
  1403. newcol.AllowSorting = false;
  1404. newcol.FilterRowEditorType = "TextBox";
  1405. newcol.FilterRowOptionsVisibility = Visibility.Collapsed;
  1406. }
  1407. newcol.FilterRowCellStyle = filterstyle;
  1408. var headstyle = new Style(typeof(GridHeaderCellControl));
  1409. headstyle.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  1410. headstyle.Setters.Add(new Setter(ForegroundProperty, new SolidColorBrush(Colors.Black)));
  1411. headstyle.Setters.Add(new Setter(FontSizeProperty, 12D));
  1412. newcol.HeaderStyle = headstyle;
  1413. var cellstyle = new Style();
  1414. if (Options.Contains(DynamicGridOption.DirectEdit))
  1415. {
  1416. if (prop.Editor is null || prop.Editor.Editable != Editable.Enabled)
  1417. {
  1418. cellstyle.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.WhiteSmoke)));
  1419. newcol.AllowEditing = false;
  1420. }
  1421. else
  1422. {
  1423. cellstyle.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.LightYellow)));
  1424. newcol.AllowEditing = true;
  1425. }
  1426. cellstyle.Setters.Add(new Setter(ForegroundProperty, new SolidColorBrush(Colors.Black)));
  1427. newcol.CellStyle = cellstyle;
  1428. }
  1429. DataGrid.Columns.Add(newcol);
  1430. ColumnList.Add(column);
  1431. }
  1432. }
  1433. LoadActionColumns(DynamicActionColumnPosition.End);
  1434. if (Summaries.Any())
  1435. {
  1436. DataGrid.CellRenderers.Remove("TableSummary");
  1437. DataGrid.CellRenderers.Add("TableSummary", new TimeSpanAggregateRenderer());
  1438. DataGrid.TableSummaryRows.Add(new GridTableSummaryRow
  1439. {
  1440. ShowSummaryInRow = false,
  1441. Position = TableSummaryRowPosition.Bottom,
  1442. SummaryColumns = Summaries
  1443. });
  1444. }
  1445. DataGrid.Columns.Resume();
  1446. DataGrid.RefreshColumns();
  1447. foreach (var key in _filterpredicates.Keys.ToArray())
  1448. if (DataGrid.Columns.Any(x => string.Equals(x.MappingName, key)))
  1449. {
  1450. var predicates = Serialization.Deserialize<List<FilterPredicate>>(_filterpredicates[key]);
  1451. foreach (var predicate in predicates)
  1452. {
  1453. DataGrid.Columns[key].FilterPredicates.Add(predicate);
  1454. DataGrid.Columns[key].FilteredFrom = FilteredFrom.FilterRow;
  1455. }
  1456. }
  1457. else
  1458. {
  1459. _filterpredicates.Remove(key);
  1460. }
  1461. ResizeColumns(DataGrid, DataGrid.ActualWidth - 2, DataGrid.ActualHeight - 2);
  1462. }
  1463. #endregion
  1464. #region Refresh / Reload
  1465. protected abstract void Reload(Filters<T> criteria, Columns<T> columns, ref SortOrder<T>? sort, Action<CoreTable?, Exception?> action);
  1466. protected virtual bool FilterRecord(CoreRow row)
  1467. {
  1468. var bOK = true;
  1469. foreach (var column in ActionColumns.Where(x => x.FilterRecord != null && x.SelectedFilters != null && x.SelectedFilters.Any()))
  1470. bOK = bOK && column.FilterRecord.Invoke(row, column.SelectedFilters);
  1471. if (bOK && OnFilterRecord is not null)
  1472. bOK = OnFilterRecord(row);
  1473. return bOK;
  1474. }
  1475. public override void Refresh(bool reloadcolumns, bool reloaddata)
  1476. {
  1477. //DataGrid.View.Filter = DoFilterRecord;
  1478. if (bRefreshing)
  1479. return;
  1480. DataGrid.SelectionForegroundBrush = BaseDynamicGrid.SelectionForeground;
  1481. DataGrid.RowSelectionBrush = BaseDynamicGrid.SelectionBackground;
  1482. var cursor = UseWaitCursor ? new WaitCursor() : null;
  1483. Loading.Visibility = Visibility.Visible;
  1484. double opacity = 1.0F;
  1485. var bFading = true;
  1486. var timer = (DispatcherTimer)Loading.Tag;
  1487. Loading.Tag = timer;
  1488. timer.Tick += (o, e) =>
  1489. {
  1490. if (bFading)
  1491. opacity -= 0.05F;
  1492. else
  1493. opacity += 0.05F;
  1494. if (opacity >= 1.0F)
  1495. {
  1496. opacity = 1.0F;
  1497. bFading = true;
  1498. }
  1499. else if (opacity <= 0.2F)
  1500. {
  1501. opacity = 0.2F;
  1502. bFading = false;
  1503. }
  1504. Loading.Opacity = opacity;
  1505. };
  1506. timer.IsEnabled = true;
  1507. bRefreshing = true;
  1508. // Yo, please don't remove this.
  1509. // The issue was when we were dynamically adding ActionColumns, and if we had to remove and then re-add them, we were getting massive performance hits
  1510. // for no reason. I think perhaps the image columns were trying to refer to data that didn't exist anymore when calling DataGrid.Columns.Refresh(),
  1511. // and thus some mega problems (perhaps even exceptions within Syncfusion) were occurring, and this seems to fix it.
  1512. // I don't pretend to know why it works; this is probably the strangest problem I've ever come across.
  1513. DataGrid.ItemsSource = null;
  1514. //using (var d = Dispatcher.DisableProcessing())
  1515. {
  1516. if (reloadcolumns)
  1517. ReloadColumns();
  1518. if (reloaddata)
  1519. {
  1520. _lookupcache.Clear();
  1521. var criteria = new Filters<T>();
  1522. var filter = DefineFilter();
  1523. if (filter != null)
  1524. criteria.Add(filter);
  1525. var columns = DataColumns();
  1526. var sort = LookupFactory.DefineSort<T>();
  1527. if (sort == null && IsSequenced)
  1528. sort = new SortOrder<T>("Sequence");
  1529. Reload(
  1530. criteria
  1531. , columns
  1532. , ref sort
  1533. , (table, exception) =>
  1534. {
  1535. if (exception != null)
  1536. {
  1537. Dispatcher.Invoke(() =>
  1538. {
  1539. MessageBox.Show(String.Format("Error: {0}", exception.Message));
  1540. });
  1541. }
  1542. else if(table is not null)
  1543. {
  1544. MasterData = table;
  1545. Dispatcher.Invoke(() =>
  1546. {
  1547. ProcessData(reloadcolumns, reloaddata);
  1548. DoAfterReload();
  1549. });
  1550. }
  1551. }
  1552. );
  1553. }
  1554. else
  1555. {
  1556. ProcessData(reloadcolumns, reloaddata);
  1557. DoAfterReload();
  1558. }
  1559. }
  1560. bRefreshing = false;
  1561. IsReady = true;
  1562. if (cursor != null)
  1563. {
  1564. cursor.Dispose();
  1565. cursor = null;
  1566. }
  1567. }
  1568. public Columns<T> DataColumns()
  1569. {
  1570. var columns = new Columns<T>();
  1571. foreach (var column in VisibleColumns)
  1572. columns.Add(column.ColumnName);
  1573. foreach (var column in HiddenColumns)
  1574. columns.Add(column);
  1575. return columns;
  1576. }
  1577. private void ProcessData(bool reloadcolumns, bool reloaddata)
  1578. {
  1579. Data.Columns.Clear();
  1580. if (MasterData != null)
  1581. foreach (var column in MasterData.Columns)
  1582. Data.Columns.Add(column);
  1583. FilterRows();
  1584. }
  1585. private readonly Dictionary<CoreRow, CoreRow> _recordmap = new();
  1586. public override void UpdateRow<TRow, TType>(CoreRow row, Expression<Func<TRow, TType>> column, TType value, bool refresh = true)
  1587. {
  1588. row.Set(column, value);
  1589. _recordmap[row].Set(column, value);
  1590. if (refresh)
  1591. InvalidateRow(row);
  1592. }
  1593. public override void UpdateRow<TType>(CoreRow row, string column, TType value, bool refresh = true)
  1594. {
  1595. row.Set(column, value);
  1596. _recordmap[row].Set(column, value);
  1597. if (refresh)
  1598. InvalidateRow(row);
  1599. }
  1600. public void AddRow(CoreRow row)
  1601. {
  1602. if (MasterData is null) return;
  1603. var masterrow = MasterData.NewRow();
  1604. MasterData.LoadRow(masterrow, row);
  1605. Refresh(false, false);
  1606. }
  1607. public void AddRow(T data)
  1608. {
  1609. if (MasterData is null) return;
  1610. var masterrow = MasterData.NewRow();
  1611. MasterData.LoadRow(masterrow, data);
  1612. MasterData.Rows.Add(masterrow);
  1613. Refresh(false, false);
  1614. }
  1615. public void DeleteRow(CoreRow row)
  1616. {
  1617. if (MasterData is null) return;
  1618. var masterrow = _recordmap[row];
  1619. MasterData.Rows.Remove(masterrow);
  1620. Refresh(false, false);
  1621. }
  1622. private void FilterRows()
  1623. {
  1624. ResetClipBuffer();
  1625. Data.Rows.Clear();
  1626. _recordmap.Clear();
  1627. if (MasterData is null)
  1628. return;
  1629. foreach (var row in MasterData.Rows)
  1630. if (FilterRecord(row))
  1631. {
  1632. var newrow = Data.NewRow();
  1633. for (var i = 0; i < Data.Columns.Count; i++)
  1634. {
  1635. var value = i < row.Values.Count ? row.Values[i] : null;
  1636. if (Data.Columns[i].DataType.IsNumeric())
  1637. value = Data.Columns[i].DataType.IsDefault(value) ? null : value;
  1638. //else if (Data.Columns[i].DataType == typeof(String[]))
  1639. // value = String.Join("\n", value as String[]);
  1640. newrow.Values.Add(value);
  1641. }
  1642. //newrow.Values.AddRange(row.Values);
  1643. //if ((OnFilterRecord == null) || (OnFilterRecord(row)))
  1644. Data.Rows.Add(newrow);
  1645. _recordmap[newrow] = row;
  1646. }
  1647. InvalidateGrid();
  1648. //ScrollBar.Value = _CurrentRow <= 0 ? 0 : _CurrentRow;
  1649. SelectedRows = new CoreRow[] { };
  1650. }
  1651. //IncrementalList<T> _data = null;
  1652. private void InvalidateRow(CoreRow row)
  1653. {
  1654. var rowdata = new List<object?>(row.Values);
  1655. foreach (var ac in ActionColumns)
  1656. rowdata.Add(ac.Image.Invoke(row));
  1657. var datarow = DataGridItems.Rows[row.Index];
  1658. for (var i = 0; i < rowdata.Count; i++)
  1659. datarow[i] = rowdata[i] ?? DBNull.Value;
  1660. //datarow.ItemArray = rowdata.ToArray();
  1661. }
  1662. private void InvalidateGrid()
  1663. {
  1664. var defaults = new List<object?>();
  1665. var result = new DataTable();
  1666. foreach (var column in Data.Columns)
  1667. {
  1668. var colname = column.ColumnName.Replace('.', '_');
  1669. if (!result.Columns.Contains(colname))
  1670. {
  1671. result.Columns.Add(colname, column.DataType);
  1672. if (!Options.Contains(DynamicGridOption.DirectEdit))
  1673. defaults.Add(column.DataType.GetDefault());
  1674. }
  1675. }
  1676. for (var i = 0; i < ActionColumns.Count; i++)
  1677. result.Columns.Add(string.Format("ActionColumn{0}", i), typeof(BitmapImage));
  1678. foreach (var row in Data.Rows)
  1679. {
  1680. var newrow = result.NewRow();
  1681. CoreRowToDataRow(newrow, row, defaults);
  1682. result.Rows.Add(newrow);
  1683. }
  1684. if (StyleSelector != null)
  1685. StyleSelector.Data = Data;
  1686. //int rowIndex = DataGrid.SelectionController.CurrentCellManager.CurrentRowColumnIndex.RowIndex;
  1687. //int columnIndex = DataGrid.SelectionController.CurrentCellManager.CurrentRowColumnIndex.ColumnIndex;
  1688. //int scrollRowIndex = DataGrid.GetVisualContainer().ScrollRows.LastBodyVisibleLineIndex;
  1689. DataGrid.ItemsSource = result;
  1690. //this.DataGrid.ScrollInView(new Syncfusion.UI.Xaml.ScrollAxis.RowColumnIndex(scrollRowIndex, columnIndex));
  1691. ResizeColumns(DataGrid, DataGrid.ActualWidth - 1, DataGrid.ActualHeight);
  1692. UpdateRecordCount();
  1693. Loading.Visibility = Visibility.Collapsed;
  1694. var timer = (DispatcherTimer)Loading.Tag;
  1695. timer.IsEnabled = false;
  1696. }
  1697. private void UpdateRecordCount()
  1698. {
  1699. var count = DataGrid.View != null ? DataGrid.View.Records.Count : Data.Rows.Count;
  1700. Count.Content = string.Format("{0} Records", count);
  1701. //Count.Visibility = _Options.Contains(DynamicGridOptions.RecordCount) && (count > 0) ? Visibility.Visible : Visibility.Collapsed;
  1702. }
  1703. public IList<CoreRow> FilteredRows()
  1704. {
  1705. var result = new List<CoreRow>();
  1706. var table = DataGridItems;
  1707. var rows = DataGrid.View.Records.Select(x => (x.Data as DataRowView)!).ToList();
  1708. foreach (var row in rows)
  1709. {
  1710. var iRow = table.Rows.IndexOf(row.Row);
  1711. result.Add(Data.Rows[iRow]);
  1712. }
  1713. return result;
  1714. }
  1715. // Doesn't appear to be used - removed 19/12/2022
  1716. /*private object?[] CreateRowValues(CoreRow row, List<object> defaults)
  1717. {
  1718. var rowdata = new List<object?>(row.Values);
  1719. foreach (var ac in ActionColumns)
  1720. rowdata.Add(ac.Image.Invoke(row));
  1721. var result = ProcessRow(rowdata, defaults);
  1722. return result.ToArray();
  1723. }*/
  1724. private void CoreRowToDataRow(DataRow newrow, CoreRow row, List<object?> defaults)
  1725. {
  1726. var rowdata = new List<object?>(row.Values);
  1727. foreach (var ac in ActionColumns)
  1728. rowdata.Add(ac.Image.Invoke(row));
  1729. try
  1730. {
  1731. var data = ProcessRow(rowdata, defaults).ToArray();
  1732. newrow.ItemArray = data;
  1733. }
  1734. catch (Exception)
  1735. {
  1736. throw;
  1737. }
  1738. }
  1739. private static IEnumerable<object?> ProcessRow(List<object?> values, List<object?> defaults)
  1740. {
  1741. if (defaults == null || !defaults.Any())
  1742. return values;
  1743. var result = new List<object?>();
  1744. for (var i = 0; i < values.Count; i++)
  1745. {
  1746. var value = values[i];
  1747. var defaultvalue = i < defaults.Count ? defaults[i] : null;
  1748. result.Add(value == null || (value.Equals(defaultvalue) && !value.GetType().IsEnum) ? null : value);
  1749. }
  1750. return result;
  1751. }
  1752. //private void LoadMoreItems(uint count, int from)
  1753. //{
  1754. // var rows = Data.Rows.Skip(from).AsQueryable().Take(50);
  1755. // _data.LoadItems(rows.Select(x => x.ToObject<T>()));
  1756. // //var list = _orders.Skip(baseIndex).Take(50).ToList();
  1757. // //IncrementalItemsSource.LoadItems(list);
  1758. //}
  1759. public override void AddVisualFilter(string column, string value)
  1760. {
  1761. if (!string.IsNullOrWhiteSpace(value))
  1762. {
  1763. DataGrid.Columns[column].FilterPredicates.Add(new FilterPredicate { FilterType = FilterType.Contains, FilterValue = value });
  1764. }
  1765. }
  1766. #endregion
  1767. #region Item Manipulation
  1768. #region Load/Save/Delete
  1769. protected virtual T[] LoadItems(CoreRow[] rows)
  1770. {
  1771. var result = new List<T>();
  1772. foreach (var row in rows)
  1773. {
  1774. var index = Data.Rows.IndexOf(row);
  1775. result.Add(LoadItem(row));
  1776. }
  1777. return result.ToArray();
  1778. }
  1779. protected abstract T LoadItem(CoreRow row);
  1780. protected abstract void SaveItem(T item);
  1781. protected virtual void SaveItems(T[] items)
  1782. {
  1783. foreach (var item in items)
  1784. SaveItem(item);
  1785. }
  1786. protected virtual bool CanDeleteItems(params CoreRow[] rows)
  1787. {
  1788. return true;
  1789. }
  1790. protected abstract void DeleteItems(params CoreRow[] rows);
  1791. protected virtual void DoDelete()
  1792. {
  1793. var rows = SelectedRows.ToArray();
  1794. if (rows.Any())
  1795. if (CanDeleteItems(rows))
  1796. if (MessageBox.Show("Are you sure you wish to delete the selected records?", "Confirm Delete", MessageBoxButton.YesNo) ==
  1797. MessageBoxResult.Yes)
  1798. {
  1799. DeleteItems(rows);
  1800. SelectedRows = Array.Empty<CoreRow>();
  1801. OnChanged?.Invoke(this);
  1802. Refresh(false, true);
  1803. SelectItems(null);
  1804. }
  1805. }
  1806. private void Delete_Click(object sender, RoutedEventArgs e)
  1807. {
  1808. DoDelete();
  1809. }
  1810. #endregion
  1811. #region Edit
  1812. protected virtual void DoEdit()
  1813. {
  1814. if (!SelectedRows.Any())
  1815. return;
  1816. var sel = SelectedRows.ToArray();
  1817. if (AddEditClick(SelectedRows))
  1818. {
  1819. InvalidateGrid();
  1820. SelectedRows = sel;
  1821. SelectItems(SelectedRows);
  1822. }
  1823. }
  1824. private void Edit_Click(object sender, RoutedEventArgs e)
  1825. {
  1826. DoEdit();
  1827. }
  1828. private void MultiEdit_Click(object sender, RoutedEventArgs e)
  1829. {
  1830. using (new WaitCursor())
  1831. {
  1832. var criteria = new Filters<T>();
  1833. var columns = new Columns<T>();
  1834. columns.Add("ID");
  1835. var iprops = DatabaseSchema.Properties(typeof(T)).Where(x => x.Editor is not NullEditor);
  1836. foreach (var iprop in iprops)
  1837. columns.Add(iprop.Name);
  1838. var sort = LookupFactory.DefineSort<T>();
  1839. Reload(
  1840. criteria,
  1841. columns,
  1842. ref sort,
  1843. (table, exception) =>
  1844. {
  1845. if(table is not null)
  1846. {
  1847. Dispatcher.Invoke(() => { DirectEdit(table); });
  1848. }
  1849. else if(exception is not null)
  1850. {
  1851. Logger.Send(LogType.Error, "", $"Error in MultiEdit: {CoreUtils.FormatException(exception)}");
  1852. MessageBox.Show(exception.Message);
  1853. }
  1854. }
  1855. );
  1856. }
  1857. }
  1858. public override bool DirectEdit(CoreTable data)
  1859. {
  1860. var window = new DynamicEditWindow<T>();
  1861. window.OnCreateItem += () => CreateItem();
  1862. window.OnCustomiseColumns += (o, c) =>
  1863. {
  1864. ConfigureColumns(MasterColumns);
  1865. if (OnCustomiseColumns != null)
  1866. return OnCustomiseColumns(this, MasterColumns);
  1867. return MasterColumns;
  1868. };
  1869. window.OnGetEditor += c =>
  1870. {
  1871. var result = GetEditor(this, c)?.CloneEditor();
  1872. if (result == null)
  1873. return null;
  1874. OnCustomiseEditor?.Invoke(window, null, c, result);
  1875. return result;
  1876. };
  1877. window.OnGetSequence += c =>
  1878. {
  1879. decimal result = 0.0M;
  1880. var customprop = DatabaseSchema.Property(typeof(T), c.ColumnName);
  1881. if (customprop != null && customprop is CustomProperty)
  1882. {
  1883. result = customprop.Sequence;
  1884. }
  1885. else
  1886. {
  1887. var bits = c.ColumnName.Split('.');
  1888. for (var i = 0; i < bits.Length; i++)
  1889. {
  1890. var sProp = string.Join(".", bits.Take(bits.Length - i));
  1891. PropertyInfo? prop;
  1892. try
  1893. {
  1894. prop = CoreUtils.GetProperty(typeof(T), sProp);
  1895. }
  1896. catch (Exception e)
  1897. {
  1898. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1899. prop = null;
  1900. }
  1901. if (prop != null)
  1902. {
  1903. result = prop.GetSequence() + result / 1000.0M;
  1904. }
  1905. else
  1906. {
  1907. var cprop = DatabaseSchema.Property(typeof(T), sProp);
  1908. if (cprop != null)
  1909. result = cprop.Sequence;
  1910. else
  1911. result /= 1000.0M;
  1912. }
  1913. }
  1914. }
  1915. return result;
  1916. };
  1917. window.Load(data);
  1918. if (window.ShowDialog() == true)
  1919. {
  1920. SaveItems(window.Updates);
  1921. return true;
  1922. }
  1923. return false;
  1924. }
  1925. protected virtual void DoAdd()
  1926. {
  1927. //CoreRow row = (SelectedRow > -1) && (SelectedRow < Data.Rows.Count) ? Data.Rows[this.SelectedRow] : null;
  1928. if (AddEditClick(null))
  1929. {
  1930. Refresh(false, true);
  1931. OnChanged?.Invoke(this);
  1932. }
  1933. }
  1934. private void Add_Click(object sender, RoutedEventArgs e)
  1935. {
  1936. DoAdd();
  1937. }
  1938. public virtual DynamicEditorPages LoadEditorPages(T item)
  1939. {
  1940. DynamicEditorPages pages = new DynamicEditorPages();
  1941. DynamicGridUtils.LoadOneToManyPages(typeof(T), pages);
  1942. DynamicGridUtils.LoadEnclosedListPages(typeof(T), pages);
  1943. DynamicGridUtils.LoadManyToManyPages(typeof(T), pages);
  1944. DynamicGridUtils.LoadCustomEditorPages(typeof(T), pages);
  1945. foreach (var page in pages)
  1946. page.Ready = false;
  1947. return pages;
  1948. }
  1949. public virtual void LoadEditorButtons(T item, DynamicEditorButtons buttons)
  1950. {
  1951. buttons.Add(
  1952. "",
  1953. Properties.Resources.help.AsBitmapImage(),
  1954. item,
  1955. (f, i) =>
  1956. {
  1957. Process.Start(new ProcessStartInfo("https://prs-software.com.au/wiki/index.php/" + typeof(T).Name.SplitCamelCase().Replace(" ", "_"))
  1958. { UseShellExecute = true });
  1959. }
  1960. );
  1961. }
  1962. protected virtual void CustomiseEditorForm(DynamicEditorForm form)
  1963. {
  1964. }
  1965. public override bool EditItems(T[] items, Func<Type, CoreTable>? PageDataHandler = null, bool PreloadPages = false)
  1966. {
  1967. var cursor = new WaitCursor();
  1968. var pages = items.Length == 1 ? LoadEditorPages(items.First()) : new DynamicEditorPages();
  1969. var buttons = new DynamicEditorButtons();
  1970. if (items.Length == 1)
  1971. LoadEditorButtons(items.First(), buttons);
  1972. var editor = new DynamicEditorForm(items.Any() ? items.First().GetType() : typeof(T), pages, buttons, PageDataHandler, PreloadPages);
  1973. editor.SetValue(Panel.ZIndexProperty, 999);
  1974. editor.OnCustomiseColumns += (o, c) =>
  1975. {
  1976. ConfigureColumns(MasterColumns /*, true */);
  1977. return MasterColumns;
  1978. };
  1979. editor.OnDefineEditor += (o, c) =>
  1980. {
  1981. var result = GetEditor(o, c);
  1982. if (result != null)
  1983. result = result.CloneEditor();
  1984. return result;
  1985. };
  1986. editor.OnFormCustomiseEditor += (o, i, c, e) => OnCustomiseEditor?.Invoke(o, (T[])i, c, e);
  1987. editor.OnDefineFilter += (sender, type) => { return DefineFilter(type, items); };
  1988. //editor.OnDefineFilter += (o, e) => { return DefineFilter(items, e); };
  1989. editor.OnDefineLookups += sender => { DefineLookups(sender, items); };
  1990. editor.OnLookupsDefined += sender => { LookupsDefined(sender, items); };
  1991. editor.OnEditorValueChanged += (s, n, v) => { return EditorValueChanged(editor, items, n, v); };
  1992. editor.ReconfigureEditors += g => { ReconfigureEditors(g, items); };
  1993. editor.OnValidateData += (o, i) => { return ValidateData(items); };
  1994. editor.OnSelectPage += SelectPage;
  1995. editor.OnGetDocument += LoadDocument;
  1996. editor.OnFindDocument += FindDocument;
  1997. editor.OnSaveDocument += SaveDocument;
  1998. editor.OnSaveItem += (o, e) =>
  1999. {
  2000. try
  2001. {
  2002. using var Wait = new WaitCursor();
  2003. OnBeforeSave?.Invoke(editor, items);
  2004. if (items.Length == 1)
  2005. editor.UnloadEditorPages(pages, items.First(), false);
  2006. foreach (var item in items)
  2007. SaveItem(item);
  2008. if (items.Length == 1)
  2009. editor.UnloadEditorPages(pages, items.First(), true);
  2010. OnAfterSave?.Invoke(editor, items);
  2011. }
  2012. catch (Exception err)
  2013. {
  2014. MessageBox.Show(err.Message);
  2015. e.Cancel = true;
  2016. }
  2017. };
  2018. CustomiseEditorForm(editor);
  2019. editor.Items = items;
  2020. AfterLoad(editor, items);
  2021. cursor.Dispose();
  2022. return editor.ShowDialog() == true;
  2023. }
  2024. private void UpdateEditor(DynamicEditorGrid grid, Expression<Func<IDimensioned, object?>> property, bool enabled)
  2025. {
  2026. if (!grid.TryFindEditor(new Column<IDimensioned>(property).Property, out var editor))
  2027. return;
  2028. editor.IsEnabled = enabled;
  2029. if (!enabled)
  2030. editor.SetValue(0D);
  2031. else
  2032. {
  2033. var value = editor.GetValue();
  2034. editor.SetValue(value);
  2035. }
  2036. }
  2037. protected virtual void ReconfigureEditors(DynamicEditorGrid grid, T[] items)
  2038. {
  2039. if (items.First() is IDimensioned dimensioned)
  2040. {
  2041. UpdateEditor(grid, x => x.Dimensions.Quantity, dimensioned.Dimensions.GetUnit().HasQuantity);
  2042. UpdateEditor(grid, x => x.Dimensions.Length, dimensioned.Dimensions.GetUnit().HasLength);
  2043. UpdateEditor(grid, x => x.Dimensions.Width, dimensioned.Dimensions.GetUnit().HasWidth);
  2044. UpdateEditor(grid, x => x.Dimensions.Height, dimensioned.Dimensions.GetUnit().HasHeight);
  2045. UpdateEditor(grid, x => x.Dimensions.Weight, dimensioned.Dimensions.GetUnit().HasWeight);
  2046. }
  2047. }
  2048. private string[]? ValidateData(T[] items)
  2049. {
  2050. var errors = new List<string>();
  2051. DoValidate(items, errors);
  2052. OnValidate?.Invoke(this, items, errors);
  2053. return errors.Any() ? errors.ToArray() : null;
  2054. }
  2055. protected virtual void DoValidate(T[] items, List<string> errors)
  2056. {
  2057. }
  2058. protected virtual void AfterLoad(DynamicEditorForm editor, T[] items)
  2059. {
  2060. }
  2061. protected virtual void SelectPage(object sender, BaseObject[]? items)
  2062. {
  2063. }
  2064. protected virtual Dictionary<string, object?> EditorValueChanged(DynamicEditorForm editor, T[] items, string name, object value)
  2065. {
  2066. var result = DynamicGridUtils.UpdateEditorValue(items, name, value);
  2067. if (OnEditorValueChanged != null)
  2068. {
  2069. var newchanges = OnEditorValueChanged(editor, name, value);
  2070. foreach (var key in newchanges.Keys)
  2071. result[key] = newchanges[key];
  2072. }
  2073. return result;
  2074. }
  2075. private readonly Dictionary<Tuple<Type, Type>, Dictionary<object, object>> _lookupcache = new();
  2076. protected virtual void LookupsDefined(ILookupEditorControl sender, T[] items)
  2077. {
  2078. }
  2079. protected virtual void DefineLookups(ILookupEditorControl sender, T[] items)
  2080. {
  2081. if (sender.EditorDefinition is not ILookupEditor editor)
  2082. return;
  2083. var colname = sender.ColumnName;
  2084. //Logger.Send(LogType.Information, typeof(T).Name, "Into Define Lookups: " + colname);
  2085. Task.Run(() =>
  2086. {
  2087. try
  2088. {
  2089. var values = editor.Values(colname, items);
  2090. Dispatcher.Invoke(
  2091. () =>
  2092. {
  2093. try
  2094. {
  2095. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  2096. sender.LoadLookups(values);
  2097. }
  2098. catch (Exception e2)
  2099. {
  2100. Logger.Send(LogType.Information, typeof(T).Name,
  2101. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  2102. }
  2103. }
  2104. );
  2105. }
  2106. catch (Exception e)
  2107. {
  2108. Logger.Send(LogType.Information, typeof(T).Name, "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  2109. }
  2110. });
  2111. }
  2112. /// <summary>
  2113. /// Retrieves an editor to display for the given column of <paramref name="item"/>.
  2114. /// </summary>
  2115. /// <param name="item">The object being edited.</param>
  2116. /// <param name="column">The column of the editor.</param>
  2117. /// <returns>A new editor, or <see langword="null"/> if no editor defined and no sensible default exists.</returns>
  2118. protected virtual BaseEditor? GetEditor(object item, DynamicGridColumn column)
  2119. {
  2120. return column.Editor ?? CoreUtils.GetProperty(item.GetType(), column.ColumnName).GetEditor();
  2121. }
  2122. protected object DefineFilter(Type type, T[] items)
  2123. {
  2124. return LookupFactory.DefineFilter(items, type);
  2125. }
  2126. protected virtual void SetEditorValue(object item, string name, object value)
  2127. {
  2128. try
  2129. {
  2130. CoreUtils.SetPropertyValue(item, name, value);
  2131. }
  2132. catch (Exception e)
  2133. {
  2134. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2135. }
  2136. }
  2137. protected virtual object? GetEditorValue(object item, string name)
  2138. {
  2139. return CoreUtils.GetPropertyValue(item, name);
  2140. }
  2141. protected virtual Document? LoadDocument(Guid id)
  2142. {
  2143. return null;
  2144. }
  2145. protected virtual Document? FindDocument(string filename)
  2146. {
  2147. return null;
  2148. }
  2149. protected virtual void SaveDocument(Document document)
  2150. {
  2151. }
  2152. private bool AddEditClick(CoreRow[]? rows)
  2153. {
  2154. if (!IsEnabled || bRefreshing)
  2155. return false;
  2156. if (rows == null || !rows.Any())
  2157. {
  2158. var item = CreateItem();
  2159. // Yea, and this won't work, because we're actually usually showing the description of a linked item,
  2160. // not the id of the link, and we need to set the ID to have it work properly :-(
  2161. //foreach (String key in VisualFilters.Keys)
  2162. // CoreUtils.SetPropertyValue(item, key, VisualFilters[key]);
  2163. if (EditItems(new[] { item }))
  2164. {
  2165. //_CurrentRow = Data.Rows.Count;
  2166. var row = Data.NewRow();
  2167. ObjectToRow(item, row);
  2168. Data.Rows.Add(row);
  2169. InvalidateGrid();
  2170. SelectedRows = new[] { row };
  2171. OnChanged?.Invoke(this);
  2172. return true;
  2173. }
  2174. return false;
  2175. }
  2176. var items = Array.Empty<T>();
  2177. using (new WaitCursor())
  2178. {
  2179. Stopwatch sw = new Stopwatch();
  2180. sw.Start();
  2181. items = LoadItems(rows);
  2182. //Logger.Send(LogType.Information, "DG:LoadItems", String.Format("Loaded Items: {0}ms", sw.ElapsedMilliseconds));
  2183. sw.Stop();
  2184. }
  2185. if (items.Any())
  2186. {
  2187. var sel = SelectedRows;
  2188. if (EditItems(items))
  2189. {
  2190. for (var i = 0; i < items.Length; i++)
  2191. ObjectToRow(items[i], rows[i]);
  2192. InvalidateGrid();
  2193. SelectedRows = sel;
  2194. OnChanged?.Invoke(this);
  2195. return true;
  2196. }
  2197. return false;
  2198. }
  2199. return false;
  2200. }
  2201. #endregion
  2202. #region Duplicate
  2203. protected virtual IEnumerable<T> LoadDuplicatorItems(CoreRow[] rows)
  2204. {
  2205. return LoadItems(rows);
  2206. }
  2207. private bool DoDuplicate(Button button, CoreRow[] rows)
  2208. {
  2209. if (!rows.Any())
  2210. {
  2211. MessageBox.Show("Please select at least one record to duplicate!");
  2212. return false;
  2213. }
  2214. /*var ids = ExtractValues(x => x.ID, Selection.Selected).ToArray();
  2215. if (!ids.Any())
  2216. {
  2217. MessageBox.Show("Please select at least one record to duplicate!");
  2218. return false;
  2219. }*/
  2220. var duplicator = (new T() as IDuplicatable)?.GetDuplicator();
  2221. if (duplicator is null)
  2222. {
  2223. MessageBox.Show($"Cannot duplicate {typeof(T)}");
  2224. return false;
  2225. }
  2226. duplicator.Duplicate(LoadDuplicatorItems(rows));// new Filter<T>(x => x.ID).InList(ids));
  2227. return true;
  2228. }
  2229. #endregion
  2230. protected virtual void ShowHelp(string slug)
  2231. {
  2232. Process.Start(new ProcessStartInfo("https://prs-software.com.au/wiki/index.php/" + slug) { UseShellExecute = true });
  2233. }
  2234. protected void ReloadForms<TTargetType, TTargetForm, TSourceForm>(DynamicEditorForm editor, TTargetType item,
  2235. Expression<Func<TSourceForm, object?>> sourcekey, Guid sourceid)
  2236. where TTargetType : Entity, new()
  2237. where TTargetForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  2238. where TSourceForm : Entity, IRemotable, IPersistent, IDigitalForm<TTargetType>, new()
  2239. {
  2240. var type = typeof(IDynamicOneToManyGrid<,>).MakeGenericType(typeof(TTargetType), typeof(TTargetForm));
  2241. var page =
  2242. editor.Pages?.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(type)) as IDynamicOneToManyGrid<TTargetType, TTargetForm>;
  2243. if (page != null && item != null)
  2244. {
  2245. if (!page.Ready)
  2246. page.Load(item, null);
  2247. CoreTable table;
  2248. if (sourceid == Guid.Empty)
  2249. {
  2250. table = new CoreTable();
  2251. table.LoadColumns(typeof(TSourceForm));
  2252. }
  2253. else
  2254. {
  2255. table = new Client<TSourceForm>().Query(
  2256. new Filter<TSourceForm>(sourcekey).IsEqualTo(sourceid).And(x => x.Form.AppliesTo)
  2257. .IsEqualTo(typeof(TTargetType).EntityName().Split('.').Last())
  2258. );
  2259. }
  2260. var newforms = new List<TTargetForm>();
  2261. foreach (var row in table.Rows)
  2262. {
  2263. var sourceform = row.ToObject<TSourceForm>();
  2264. var targetform = new TTargetForm();
  2265. targetform.Form.ID = sourceform.Form.ID;
  2266. targetform.Form.Synchronise(sourceform.Form);
  2267. newforms.Add(targetform);
  2268. }
  2269. page.Items.Clear();
  2270. page.LoadItems(newforms.ToArray());
  2271. }
  2272. }
  2273. #region ClipBuffer
  2274. private Tuple<ClipAction, CoreRow[]>? ClipBuffer;
  2275. protected void ResetClipBuffer()
  2276. {
  2277. ClipBuffer = null;
  2278. }
  2279. protected void SetClipBuffer(ClipAction action, CoreRow[] rows)
  2280. {
  2281. ClipBuffer = new Tuple<ClipAction, CoreRow[]>(action, rows);
  2282. }
  2283. private void CutToClipBuffer()
  2284. {
  2285. SetClipBuffer(ClipAction.Cut, SelectedRows);
  2286. InvalidateGrid();
  2287. }
  2288. private void CopyToClipBuffer()
  2289. {
  2290. SetClipBuffer(ClipAction.Copy, SelectedRows);
  2291. InvalidateGrid();
  2292. }
  2293. private void PasteFromClipBuffer()
  2294. {
  2295. if (ClipBuffer == null)
  2296. return;
  2297. if (!IsSequenced)
  2298. return;
  2299. using (new WaitCursor())
  2300. {
  2301. var updates = ClipBuffer.Item2.Select(x => x.ToObject<T>()).ToList();
  2302. if (BeforePaste(updates, ClipBuffer.Item1))
  2303. {
  2304. var currow = SelectedRows.FirstOrDefault()
  2305. ?? Data.Rows.LastOrDefault();
  2306. var sequence = currow != null ? currow.Get<T, long>(c => ((ISequenceable)c).Sequence) : 0;
  2307. var postrows = Data.Rows.Where(r => !ClipBuffer.Item2.Contains(r) && r.Get<ISequenceable, long>(x => x.Sequence) >= sequence);
  2308. updates.AddRange(LoadItems(postrows.ToArray()));
  2309. foreach (var update in updates)
  2310. {
  2311. sequence++;
  2312. ((ISequenceable)update).Sequence = sequence;
  2313. }
  2314. }
  2315. if (updates.Any())
  2316. {
  2317. SaveItems(updates.ToArray());
  2318. Refresh(false, true);
  2319. }
  2320. }
  2321. }
  2322. protected virtual bool BeforePaste(IEnumerable<T> items, ClipAction action)
  2323. {
  2324. return true;
  2325. }
  2326. private void Cut_Click(object sender, RoutedEventArgs e)
  2327. {
  2328. CutToClipBuffer();
  2329. }
  2330. private void Copy_Click(object sender, RoutedEventArgs e)
  2331. {
  2332. CopyToClipBuffer();
  2333. }
  2334. private void Paste_Click(object sender, RoutedEventArgs e)
  2335. {
  2336. PasteFromClipBuffer();
  2337. }
  2338. #endregion
  2339. protected virtual void ObjectToRow(T obj, CoreRow row)
  2340. {
  2341. Data.LoadRow(row, obj);
  2342. }
  2343. #region Import / Export
  2344. protected virtual Guid GetImportID()
  2345. {
  2346. return Guid.Empty;
  2347. }
  2348. protected virtual bool CustomiseImportItem(T item)
  2349. {
  2350. if (IsSequenced)
  2351. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  2352. return true;
  2353. }
  2354. protected virtual string CustomiseImportFileName(string filename)
  2355. {
  2356. return filename;
  2357. }
  2358. private void Import_Click(object sender, RoutedEventArgs e)
  2359. {
  2360. var list = new DynamicImportList(
  2361. typeof(T),
  2362. GetImportID()
  2363. );
  2364. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  2365. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  2366. list.ShowDialog();
  2367. Refresh(false, true);
  2368. }
  2369. protected virtual void CustomiseExportColumns(List<string> columnnames)
  2370. {
  2371. }
  2372. protected virtual string CustomiseExportFileName(string filename)
  2373. {
  2374. return filename;
  2375. }
  2376. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  2377. {
  2378. }
  2379. protected virtual void ApplyExportFilter(CoreTable table, object data)
  2380. {
  2381. }
  2382. private void Export_Click(object sender, RoutedEventArgs e)
  2383. {
  2384. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  2385. CustomiseExportColumns(columnnames);
  2386. var form = new DynamicExportForm(typeof(T), columnnames);
  2387. if (form.ShowDialog() != true)
  2388. return;
  2389. var filters = new Filters<T>();
  2390. filters.Add(DefineFilter());
  2391. var visiblerows = GetVisibleRows();
  2392. CustomiseExportFilters(filters, visiblerows);
  2393. var columns = new Columns<T>(form.Fields);
  2394. var otherColumns = form.GetChildFields()
  2395. .Select(x => new Tuple<Type, IColumns>(
  2396. x.Key,
  2397. (Activator.CreateInstance(typeof(Columns<>).MakeGenericType(x.Key), new object[] { x.Value }) as IColumns)!))
  2398. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  2399. var sort = LookupFactory.DefineSort<T>();
  2400. Reload(filters, columns, ref sort, (data, err) => Dispatcher.Invoke(() => {
  2401. if(data is not null)
  2402. {
  2403. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), data) };
  2404. list.AddRange(LoadExportTables(filters, otherColumns));
  2405. DoExport(list);
  2406. }
  2407. else if (err is not null)
  2408. {
  2409. Logger.Send(LogType.Error, "", $"Error in export: {CoreUtils.FormatException(err)}");
  2410. MessageBox.Show(err.Message);
  2411. }
  2412. }));
  2413. }
  2414. /// <summary>
  2415. /// Loads the child tables for an export, based on the filter of the parent table.
  2416. /// </summary>
  2417. /// <remarks>
  2418. /// If not overriden, defaults to creating empty tables with no records.
  2419. /// </remarks>
  2420. /// <param name="filter">Filter for the parent table.</param>
  2421. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  2422. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  2423. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  2424. {
  2425. return tableColumns.Select(x => {
  2426. var table = new CoreTable();
  2427. table.LoadColumns(x.Item2);
  2428. return new Tuple<Type?, CoreTable>(x.Item1, table);
  2429. });
  2430. }
  2431. private void DoExport(List<Tuple<Type?, CoreTable>> data)
  2432. {
  2433. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  2434. ExcelExporter.DoExport(data, filename);
  2435. }
  2436. #endregion
  2437. public void ScrollIntoView(CoreRow row)
  2438. {
  2439. DataGrid.ScrollInView(new RowColumnIndex(row.Index + 1, 0));
  2440. }
  2441. #endregion
  2442. #region Custom Buttons
  2443. private Button CreateButton(BitmapImage? image = null, string? text = null, string? tooltip = null)
  2444. {
  2445. var button = new Button();
  2446. button.SetValue(BorderBrushProperty, new SolidColorBrush(Colors.Gray));
  2447. button.SetValue(BorderThicknessProperty, new Thickness(0.75));
  2448. button.Height = 30;
  2449. UpdateButton(button, image, text, tooltip);
  2450. return button;
  2451. }
  2452. protected void UpdateButton(Button button, BitmapImage? image, string? text, string? tooltip = null)
  2453. {
  2454. var stackPnl = new StackPanel();
  2455. stackPnl.Orientation = Orientation.Horizontal;
  2456. //stackPnl.Margin = new Thickness(2);
  2457. if (image != null)
  2458. {
  2459. var img = new Image();
  2460. img.Source = image;
  2461. img.Margin = new Thickness(2);
  2462. img.ToolTip = tooltip;
  2463. stackPnl.Children.Add(img);
  2464. }
  2465. if (!string.IsNullOrEmpty(text))
  2466. {
  2467. var lbl = new Label();
  2468. lbl.Content = text;
  2469. lbl.VerticalAlignment = VerticalAlignment.Stretch;
  2470. lbl.VerticalContentAlignment = VerticalAlignment.Center;
  2471. lbl.Margin = new Thickness(2, 0, 5, 0);
  2472. lbl.ToolTip = ToolTip;
  2473. stackPnl.Children.Add(lbl);
  2474. }
  2475. button.Content = stackPnl;
  2476. button.ToolTip = tooltip;
  2477. }
  2478. private bool bFirstButtonAdded = true;
  2479. private bool AnyButtonsVisible()
  2480. {
  2481. if (Add.Visibility != Visibility.Collapsed)
  2482. return true;
  2483. if (Edit.Visibility != Visibility.Collapsed)
  2484. return true;
  2485. if (MultiEdit.Visibility != Visibility.Collapsed)
  2486. return true;
  2487. if (Export.Visibility != Visibility.Collapsed)
  2488. return true;
  2489. return false;
  2490. }
  2491. public Button AddButton(string caption, BitmapImage? image, string? tooltip, Func<Button, CoreRow[], bool> action)
  2492. {
  2493. var button = CreateButton(image, caption, tooltip);
  2494. button.Margin = new Thickness(bFirstButtonAdded && AnyButtonsVisible() ? /* 10 */ 0 : 0, 2, 2, 0);
  2495. button.Padding = new Thickness(5, 0, 5, 0);
  2496. button.Tag = action;
  2497. button.Click += Button_Click;
  2498. Stack.Children.Add(button);
  2499. bFirstButtonAdded = false;
  2500. return button;
  2501. }
  2502. public Button AddButton(string caption, BitmapImage? image, Func<Button, CoreRow[], bool> action)
  2503. {
  2504. var result = AddButton(caption, image, null, action);
  2505. return result;
  2506. }
  2507. private void Button_Click(object sender, RoutedEventArgs e)
  2508. {
  2509. var button = (Button)sender;
  2510. var action = (Func<Button, CoreRow[], bool>)button.Tag;
  2511. //CoreRow row = (CurrentRow > -1) && (CurrentRow < Data.Rows.Count) ? Data.Rows[this.CurrentRow] : null;
  2512. if (action.Invoke(button, SelectedRows))
  2513. Refresh(false, true);
  2514. }
  2515. #endregion
  2516. #region Header Actions
  2517. private void SelectColumnsClick(object sender, RoutedEventArgs e)
  2518. {
  2519. var editor = new DynamicGridColumnsEditor(typeof(T));
  2520. editor.DirectEdit = Options.Contains(DynamicGridOption.DirectEdit);
  2521. editor.Columns.AddRange(VisibleColumns);
  2522. if (editor.ShowDialog().Equals(true))
  2523. {
  2524. VisibleColumns.Clear();
  2525. VisibleColumns.AddRange(editor.Columns);
  2526. SaveColumns(VisibleColumns);
  2527. //OnSaveColumns?.Invoke(this, editor.Columns);
  2528. Refresh(true, true);
  2529. }
  2530. }
  2531. #endregion
  2532. /* Removed as appears unused; removed as of 19/12/2022
  2533. #region CellRendering
  2534. private void PopulateDynamicActionCell(DynamicActionColumn column, int rowIndex, int columnIndex, GridStyleInfo style)
  2535. {
  2536. style.CellType = "ImageCell";
  2537. var bi = column.Image?.Invoke(rowIndex < 0 ? null : Data.Rows[rowIndex]);
  2538. if (bi != null)
  2539. {
  2540. style.CellValue = bi;
  2541. style.BorderMargins = new CellMarginsInfo(4.0F);
  2542. }
  2543. }
  2544. //bool rowstylehelperinitialised = false;
  2545. //protected virtual void ProcessCellStyle(CoreRow row, int column, GridStyleInfo style)
  2546. //{
  2547. // if (!rowstylehelperinitialised)
  2548. // {
  2549. // Script stylescript = new Client<Script>().Load(new Filter<Script>(x => x.Section).IsEqualTo(typeof(T).EntityName()).And(x => x.ScriptType).IsEqualTo(ScriptType.RowStyle)).FirstOrDefault(); ;
  2550. // if (stylescript != null)
  2551. // {
  2552. // rowstylehelper = new ScriptDocument(stylescript.Code);
  2553. // if (!rowstylehelper.Compile())
  2554. // {
  2555. // MessageBox.Show("Unable to Load Row Style Helper!\r\n\r\n" + rowstylehelper.Result);
  2556. // rowstylehelper = null;
  2557. // }
  2558. // }
  2559. // rowstylehelperinitialised = true;
  2560. // }
  2561. // if (rowstylehelper != null)
  2562. // {
  2563. // try
  2564. // {
  2565. // rowstylehelper.SetValue("Row", row);
  2566. // rowstylehelper.SetValue("Column", Data.Columns[column].ColumnName);
  2567. // rowstylehelper.SetValue("Background", style.Background);
  2568. // rowstylehelper.SetValue("Foreground", style.Foreground);
  2569. // rowstylehelper.SetValue("Style", style.Font.FontStyle);
  2570. // rowstylehelper.SetValue("Weight", style.Font.FontWeight);
  2571. // if (rowstylehelper.Execute())
  2572. // {
  2573. // style.Background = (System.Windows.Media.Brush)rowstylehelper.GetValue("Background");
  2574. // style.Foreground = (System.Windows.Media.Brush)rowstylehelper.GetValue("Foreground");
  2575. // style.Font.FontStyle = (FontStyle)rowstylehelper.GetValue("Style");
  2576. // style.Font.FontWeight = (FontWeight)rowstylehelper.GetValue("Weight");
  2577. // }
  2578. // }
  2579. // catch (Exception e)
  2580. // {
  2581. // //MessageBox.Show("Unable to Invoke Row Style Helper!\r\n\r\n" + e.Message);
  2582. // }
  2583. // }
  2584. //}
  2585. private readonly Dictionary<string, BaseEditor> editorcache = new();
  2586. private void PopulateDataCell(int rowIndex, int columnIndex, GridStyleInfo style)
  2587. {
  2588. if (columnIndex > -1 && columnIndex < ColumnList.Count)
  2589. {
  2590. var o = ColumnList[columnIndex];
  2591. if (o is DynamicActionColumn)
  2592. {
  2593. PopulateDynamicActionCell((DynamicActionColumn)o, rowIndex, columnIndex, style);
  2594. }
  2595. else
  2596. {
  2597. var dgc = (DynamicGridColumn)o;
  2598. var dc = Data.Columns.FirstOrDefault(x => x.ColumnName.Equals(dgc.ColumnName));
  2599. var fmt = string.IsNullOrWhiteSpace(dgc.Format) ? "{0}" : "{0:" + dgc.Format.Replace("\\:", ":").Replace(":", "\\:") + "}";
  2600. object? val = null;
  2601. if (rowIndex < Data.Rows.Count)
  2602. val = Data.Rows[rowIndex][dgc.ColumnName];
  2603. if (val != null && dgc.Lookups.ContainsKey(val))
  2604. val = dgc.Lookups[val];
  2605. if (dc != null)
  2606. {
  2607. if(!editorcache.TryGetValue(dc.ColumnName, out var editor))
  2608. {
  2609. var prop = DatabaseSchema.Property(typeof(T), dc.ColumnName);
  2610. if (prop != null)
  2611. editor = prop.Editor;
  2612. else
  2613. editor = EditorUtils.GetEditor(dc.DataType) ?? new NullEditor();
  2614. editorcache[dc.ColumnName] = editor;
  2615. }
  2616. if (editor is CheckBoxEditor)
  2617. {
  2618. style.CellType = "CheckBox";
  2619. style.CellValue = val;
  2620. style.HorizontalAlignment = dc == null ? HorizontalAlignment.Left : dgc.HorizontalAlignment(dc.DataType);
  2621. style.VerticalAlignment = dgc.VerticalAlignment();
  2622. style.TextMargins = new CellMarginsInfo(2.0F);
  2623. }
  2624. else if (editor is ColorEditor)
  2625. {
  2626. style.CellType = "ImageCell";
  2627. var str = val?.ToString();
  2628. if (!string.IsNullOrWhiteSpace(str))
  2629. {
  2630. var color = ColorTranslator.FromHtml(str); // System.Drawing.Color.FromName(val.ToString());
  2631. var bitmap = ImageUtils.BitmapFromColor(color, (int)style.GridModel.ColumnWidths[columnIndex],
  2632. (int)style.GridModel.RowHeights[rowIndex], Color.Black);
  2633. //bitmap.Save(val.ToString().Replace("#","") + ".png");
  2634. style.CellValue = bitmap.AsBitmapImage(false);
  2635. style.BorderMargins = new CellMarginsInfo(4.0F);
  2636. }
  2637. }
  2638. else
  2639. {
  2640. string value;
  2641. try
  2642. {
  2643. if(val is null)
  2644. {
  2645. value = "";
  2646. }
  2647. else if (val.GetType().IsEnum)
  2648. {
  2649. value = val.ToString()!;
  2650. }
  2651. else if (val.GetType().IsDefault(val))
  2652. {
  2653. value = "";
  2654. }
  2655. else
  2656. {
  2657. value = string.Format(new TimeSpanFormatter(), fmt, val);
  2658. }
  2659. }
  2660. catch (Exception e)
  2661. {
  2662. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2663. value = val?.ToString() ?? "";
  2664. }
  2665. if (editor is PasswordEditor)
  2666. style.CellValue = "".PadLeft(value.Length, '●');
  2667. else
  2668. style.CellValue = value;
  2669. style.HorizontalAlignment = dc == null ? HorizontalAlignment.Left : dgc.HorizontalAlignment(dc.DataType);
  2670. style.VerticalAlignment = dgc.VerticalAlignment();
  2671. style.CellType = "Static";
  2672. style.TextMargins = new CellMarginsInfo(2.0F);
  2673. }
  2674. }
  2675. }
  2676. }
  2677. }
  2678. private void PopulateHeaderCell(int columnIndex, GridStyleInfo style)
  2679. {
  2680. if (columnIndex > -1 && columnIndex < ColumnList.Count)
  2681. {
  2682. var o = ColumnList[columnIndex];
  2683. if (o is DynamicActionColumn)
  2684. {
  2685. PopulateDynamicActionCell((DynamicActionColumn)o, -1, columnIndex, style);
  2686. }
  2687. else
  2688. {
  2689. var dgc = (DynamicGridColumn)o;
  2690. if (Data != null)
  2691. {
  2692. var dc = Data.Columns.FirstOrDefault(x => x.ColumnName.Equals(dgc.ColumnName));
  2693. style.HorizontalAlignment = dc != null ? dgc.HorizontalAlignment(dc.DataType) : HorizontalAlignment.Left;
  2694. }
  2695. style.CellValue = string.IsNullOrWhiteSpace(dgc.Caption) ? dgc.ColumnName : dgc.Caption;
  2696. style.VerticalAlignment = dgc.VerticalAlignment();
  2697. style.CellType = "Static";
  2698. style.TextMargins = new CellMarginsInfo(2.0F);
  2699. }
  2700. }
  2701. }
  2702. #endregion
  2703. */
  2704. /* Removed as appears unused; removed as of 19/12/2022
  2705. #region Drag and Drop
  2706. private Point startpoint;
  2707. private void CheckPreviewMouseDown(object sender, MouseButtonEventArgs e)
  2708. {
  2709. if (!Options.Contains(DynamicGridOption.DragSource))
  2710. return;
  2711. if (e.LeftButton == MouseButtonState.Pressed)
  2712. {
  2713. Logger.Send(LogType.Information, GetType().EntityName(), "Initiating Start Point");
  2714. startpoint = e.GetPosition(DataGrid);
  2715. }
  2716. }
  2717. //private void CheckPreviewMouseMove(object sender, MouseEventArgs e)
  2718. //{
  2719. // Logger.Send(LogType.Information, this.GetType().EntityName(), String.Format("Checking Mouse Move: StartPoint = {0},{1}", startpoint.X, startpoint.Y));
  2720. // if (!_Options.Contains(DynamicGridOptions.DragSource))
  2721. // return;
  2722. // Vector diff = startpoint - e.GetPosition(null);
  2723. // Logger.Send(LogType.Information, this.GetType().EntityName(), String.Format("Checking Mouse Move: StartPoint = {0},{1} Diff = {2},{3}", startpoint.X, startpoint.Y, diff.X, diff.Y));
  2724. // if ( (startpoint.X != 0) && (startpoint.Y != 0))
  2725. // {
  2726. // if ((Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance) || (Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
  2727. // {
  2728. // Logger.Send(LogType.Information, this.GetType().EntityName(), "Starting Drag Drop Operation");
  2729. // DataObject dragData = new DataObject(typeof(T).EntityName(), SelectedRows);
  2730. // DragDrop.DoDragDrop(DataGrid, dragData, DragDropEffects.Copy);
  2731. // }
  2732. // }
  2733. //}
  2734. private void CheckPreviewMouseUp(object sender, MouseButtonEventArgs e)
  2735. {
  2736. if (!Options.Contains(DynamicGridOption.DragSource))
  2737. return;
  2738. Logger.Send(LogType.Information, GetType().EntityName(), "Clearing Start Point");
  2739. startpoint = new Point();
  2740. }
  2741. #endregion
  2742. */
  2743. }
  2744. }