DynamicGrid.cs 154 KB

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