DynamicGrid.cs 142 KB

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