DynamicGrid.cs 147 KB

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