DynamicGrid.cs 155 KB

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