DynamicGrid.cs 143 KB

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