DynamicGrid.cs 147 KB

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