DynamicGrid.cs 156 KB

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