DynamicGrid.cs 147 KB

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