DynamicGrid.cs 141 KB

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