DynamicGrid.cs 147 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725
  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. public 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(true, 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. if (imgcol.VerticalHeader)
  1252. headstyle.Setters.Add(new Setter(TemplateProperty,
  1253. Application.Current.Resources["VerticalColumnHeader"] as ControlTemplate));
  1254. }
  1255. else
  1256. {
  1257. var image = imgcol.Image?.Invoke(null);
  1258. if (image != null)
  1259. {
  1260. var template = new ControlTemplate(typeof(GridHeaderCellControl));
  1261. var border = new FrameworkElementFactory(typeof(Border));
  1262. border.SetValue(Border.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro));
  1263. border.SetValue(Border.PaddingProperty, new Thickness(4));
  1264. border.SetValue(MarginProperty, new Thickness(0, 0, 1, 1));
  1265. var img = new FrameworkElementFactory(typeof(Image));
  1266. img.SetValue(Image.SourceProperty, image);
  1267. border.AppendChild(img);
  1268. template.VisualTree = border;
  1269. headstyle.Setters.Add(new Setter(TemplateProperty, template));
  1270. }
  1271. }
  1272. newcol.HeaderStyle = headstyle;
  1273. DataGrid.Columns.Add(newcol);
  1274. ColumnList.Add(column);
  1275. }
  1276. else if (column is DynamicTextColumn txtCol)
  1277. {
  1278. var newcol = new GridTextColumn();
  1279. gridRowResizingOptions.ExcludeColumns.Add(sColName);
  1280. newcol.TextWrapping = TextWrapping.NoWrap;
  1281. newcol.TextAlignment = txtCol.Alignment == Alignment.NotSet
  1282. ? TextAlignment.Left
  1283. : txtCol.Alignment == Alignment.BottomLeft || txtCol.Alignment == Alignment.MiddleLeft ||
  1284. txtCol.Alignment == Alignment.TopLeft
  1285. ? TextAlignment.Left
  1286. : txtCol.Alignment == Alignment.BottomCenter || txtCol.Alignment == Alignment.MiddleCenter ||
  1287. txtCol.Alignment == Alignment.TopCenter
  1288. ? TextAlignment.Center
  1289. : TextAlignment.Right;
  1290. newcol.AllowEditing = false;
  1291. newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
  1292. newcol.MappingName = sColName;
  1293. newcol.Width = column.Width == 0 ? DataGrid.RowHeight : column.Width;
  1294. newcol.ColumnSizer = GridLengthUnitType.None;
  1295. newcol.HeaderText = column.HeaderText;
  1296. newcol.AllowFiltering = column.Filters != null && column.Filters.Any();
  1297. newcol.AllowSorting = false;
  1298. newcol.FilterRowOptionsVisibility = Visibility.Collapsed;
  1299. newcol.ShowToolTip = column.ToolTip != null;
  1300. var style = new Style();
  1301. style.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  1302. style.Setters.Add(new Setter(IsEnabledProperty, false));
  1303. newcol.FilterRowCellStyle = style;
  1304. var headstyle = new Style(typeof(GridHeaderCellControl));
  1305. headstyle.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  1306. headstyle.Setters.Add(new Setter(ForegroundProperty, new SolidColorBrush(Colors.Black)));
  1307. headstyle.Setters.Add(new Setter(FontSizeProperty, 12D));
  1308. headstyle.Setters.Add(new Setter(MarginProperty, new Thickness(0, -0.75, 0, 0.75)));
  1309. headstyle.Setters.Add(new Setter(BorderThicknessProperty, new Thickness(0.75)));
  1310. if (txtCol.VerticalHeader)
  1311. {
  1312. headstyle.Setters.Add(new Setter(HorizontalContentAlignmentProperty, HorizontalAlignment.Left));
  1313. headstyle.Setters.Add(new Setter(TemplateProperty,
  1314. Application.Current.Resources["VerticalColumnHeader"] as ControlTemplate));
  1315. }
  1316. newcol.HeaderStyle = headstyle;
  1317. DataGrid.Columns.Add(newcol);
  1318. ColumnList.Add(column);
  1319. }
  1320. }
  1321. }
  1322. }
  1323. private bool CanSort()
  1324. {
  1325. return !IsSequenced;
  1326. }
  1327. private void ReloadColumns()
  1328. {
  1329. ConfigureColumns(MasterColumns /*, false */);
  1330. VisibleColumns = LoadColumns();
  1331. ConfigureColumns(VisibleColumns /*, true */);
  1332. DataGrid.Columns.Suspend();
  1333. ColumnList.Clear();
  1334. DataGrid.Columns.Clear();
  1335. DataGrid.TableSummaryRows.Clear();
  1336. var Summaries = new ObservableCollection<ISummaryColumn>();
  1337. gridRowResizingOptions.ExcludeColumns = new List<string>();
  1338. LoadActionColumns(DynamicActionColumnPosition.Start);
  1339. foreach (var column in VisibleColumns)
  1340. {
  1341. var filtering = true;
  1342. IProperty? prop;
  1343. try
  1344. {
  1345. prop = DatabaseSchema.Property(typeof(T), column.ColumnName);
  1346. }
  1347. catch (Exception e)
  1348. {
  1349. Logger.Send(LogType.Error, ClientFactory.UserID,
  1350. string.Format("Error constructing Column [{0}] : {1}\n{2}", column.ColumnName, e.Message, e.StackTrace));
  1351. prop = null;
  1352. }
  1353. if (prop != null)
  1354. {
  1355. var scolname = column.ColumnName.Replace('.', '_');
  1356. GridColumn newcol;
  1357. if (prop.PropertyType.IsNumeric())
  1358. {
  1359. var digits = 0;
  1360. var prefix = "N";
  1361. if (column.Editor is CurrencyEditor currencyEditor)
  1362. {
  1363. var curcol = new GridCurrencyColumn();
  1364. if (!prop.PropertyType.IsOrdinal())
  1365. {
  1366. var format = string.IsNullOrWhiteSpace(column.Format) ? "" : column.Format.Replace("C", "");
  1367. if (!int.TryParse(format, out digits))
  1368. digits = currencyEditor.Digits;
  1369. }
  1370. curcol.CurrencyDecimalDigits = digits;
  1371. curcol.CurrencyGroupSeparator = ",";
  1372. curcol.CurrencyGroupSizes = new Int32Collection(new[] { 3, 3, 3, 3, 3, 3 });
  1373. prefix = "C";
  1374. newcol = curcol;
  1375. }
  1376. else
  1377. {
  1378. var numcol = new GridNumericColumn();
  1379. if (!prop.PropertyType.IsOrdinal())
  1380. {
  1381. var format = string.IsNullOrWhiteSpace(column.Format) ? "" : column.Format.Replace("F", "");
  1382. if (!int.TryParse(format, out digits))
  1383. digits = column.Editor is DoubleEditor doubleEditor ? doubleEditor.Digits : 0;
  1384. numcol.NumberDecimalDigits = digits;
  1385. numcol.NumberGroupSeparator = ",";
  1386. numcol.NumberGroupSizes = new Int32Collection(new[] { 3, 3, 3, 3, 3, 3 });
  1387. }
  1388. else
  1389. {
  1390. numcol.NumberGroupSeparator = "";
  1391. numcol.NumberDecimalDigits = 0;
  1392. }
  1393. prefix = "N";
  1394. newcol = numcol;
  1395. }
  1396. if (prop.Editor.Summary != Summary.None)
  1397. {
  1398. var summary = new GridSummaryColumn
  1399. {
  1400. Name = scolname,
  1401. Format = "{" + (prop.Editor.Summary == Summary.Sum ? "Sum" : "Count") + ":" +
  1402. string.Format("{0}{1}", prefix, digits) +
  1403. "}",
  1404. MappingName = scolname,
  1405. SummaryType = prop.Editor.Summary == Summary.Sum
  1406. ? prop.PropertyType.IsOrdinal() ? SummaryType.Int32Aggregate : SummaryType.DoubleAggregate
  1407. : SummaryType.CountAggregate
  1408. };
  1409. Summaries.Add(summary);
  1410. }
  1411. }
  1412. else if (prop.PropertyType == typeof(DateTime))
  1413. {
  1414. newcol = new GridDateTimeColumn
  1415. {
  1416. CustomPattern = column.Format,
  1417. Pattern = !string.IsNullOrWhiteSpace(column.Format) ? DateTimePattern.CustomPattern : DateTimePattern.ShortDate
  1418. };
  1419. }
  1420. else if (prop.PropertyType == typeof(TimeSpan))
  1421. {
  1422. newcol = new GridTimeSpanColumn
  1423. {
  1424. DisplayBinding = new Binding
  1425. {
  1426. Path = new PropertyPath(scolname),
  1427. Converter = new TimeSpanToStringConverter(column.Format)
  1428. },
  1429. Format = column.Format, //.Replace(":", "':'"),
  1430. ShowArrowButtons = false
  1431. };
  1432. filtering = false;
  1433. if (prop.Editor != null && prop.Editor.Summary != Summary.None)
  1434. {
  1435. var summary = new GridSummaryColumn
  1436. {
  1437. Name = scolname,
  1438. Format = "{" + (prop.Editor.Summary == Summary.Sum
  1439. ? "Sum" + (string.IsNullOrWhiteSpace(column.Format) ? "" : ":" + column.Format.Replace(":", "':'"))
  1440. : prop.Editor.Summary == Summary.Count
  1441. ? "Count"
  1442. : "") + "}",
  1443. MappingName = scolname,
  1444. SummaryType = prop.Editor.Summary == Summary.Sum ? SummaryType.Custom : SummaryType.CountAggregate,
  1445. CustomAggregate = new TimeSpanAggregate()
  1446. };
  1447. Summaries.Add(summary);
  1448. }
  1449. }
  1450. else if (prop.PropertyType == typeof(bool))
  1451. {
  1452. if (Options.Contains(DynamicGridOption.DirectEdit))
  1453. {
  1454. var checkcol = new GridCheckBoxColumn
  1455. {
  1456. ValueBinding = new Binding
  1457. {
  1458. Path = new PropertyPath(scolname)
  1459. },
  1460. IsThreeState = false
  1461. };
  1462. newcol = checkcol;
  1463. }
  1464. else
  1465. {
  1466. var imgcol = new GridImageColumn
  1467. {
  1468. ValueBinding = new Binding
  1469. {
  1470. Path = new PropertyPath(scolname),
  1471. Converter = new BoolToImageConverter()
  1472. },
  1473. ImageHeight = DataGrid.RowHeight - 8,
  1474. ImageWidth = DataGrid.RowHeight - 8,
  1475. Padding = new Thickness(4)
  1476. };
  1477. newcol = imgcol;
  1478. }
  1479. gridRowResizingOptions.ExcludeColumns.Add(scolname);
  1480. filtering = false;
  1481. }
  1482. else if (prop.Editor is ColorEditor)
  1483. {
  1484. var imgcol = new GridImageColumn
  1485. {
  1486. ValueBinding = new Binding
  1487. {
  1488. Path = new PropertyPath(scolname),
  1489. Converter = new StringToColorImageConverter(column.Width - 8, (int)DataGrid.RowHeight - 8)
  1490. },
  1491. ImageHeight = DataGrid.RowHeight - 8,
  1492. ImageWidth = column.Width - 8,
  1493. Padding = new Thickness(4)
  1494. };
  1495. gridRowResizingOptions.ExcludeColumns.Add(scolname);
  1496. newcol = imgcol;
  1497. filtering = false;
  1498. }
  1499. else if (prop.Editor is ILookupEditor lookupEditor)
  1500. {
  1501. var lookupcol = new GridComboBoxColumn();
  1502. //var lookups = editor.Values(column.ColumnName).ToDictionary(column.ColumnName, "Display");
  1503. //lookupcol.SelectedValuePath = "Key";
  1504. //lookupcol.DisplayMemberPath = "Value";
  1505. //lookupcol.ItemsSource = lookups;
  1506. var table = lookupEditor.Values(column.ColumnName).ToDataTable();
  1507. lookupcol.SelectedValuePath = table.Columns[0].ColumnName;
  1508. lookupcol.DisplayMemberPath = "Display";
  1509. lookupcol.ItemsSource = table.DefaultView;
  1510. newcol = lookupcol;
  1511. }
  1512. else
  1513. {
  1514. var textcol = new GridTextColumn();
  1515. if (!(prop.Editor is MemoEditor))
  1516. gridRowResizingOptions.ExcludeColumns.Add(scolname);
  1517. textcol.TextWrapping = TextWrapping.NoWrap;
  1518. newcol = textcol;
  1519. if (prop.PropertyType == typeof(string[]))
  1520. newcol.DisplayBinding = new Binding { Path = new PropertyPath(scolname), Converter = new StringArrayConverter() };
  1521. textcol.AllowEditing = Options.Contains(DynamicGridOption.DirectEdit);
  1522. textcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
  1523. }
  1524. DataGrid.SummaryCalculationUnit = SummaryCalculationUnit.AllRows;
  1525. DataGrid.LiveDataUpdateMode = LiveDataUpdateMode.AllowSummaryUpdate;
  1526. newcol.MappingName = scolname;
  1527. newcol.Width = column.Width; // != 0 ? column.Width : double.NaN;
  1528. newcol.ColumnSizer =
  1529. GridLengthUnitType.None; //column.Width != 0 ? GridLengthUnitType.None : GridLengthUnitType.AutoWithLastColumnFill;
  1530. newcol.HeaderText = string.IsNullOrWhiteSpace(column.Caption) ? column.ColumnName : column.Caption;
  1531. newcol.TextAlignment = column.Alignment == Alignment.NotSet
  1532. ? prop.PropertyType.IsNumeric() ? TextAlignment.Right : TextAlignment.Left
  1533. : column.Alignment == Alignment.BottomLeft || column.Alignment == Alignment.MiddleLeft ||
  1534. column.Alignment == Alignment.TopLeft
  1535. ? TextAlignment.Left
  1536. : column.Alignment == Alignment.BottomCenter || column.Alignment == Alignment.MiddleCenter ||
  1537. column.Alignment == Alignment.TopCenter
  1538. ? TextAlignment.Center
  1539. : TextAlignment.Right;
  1540. newcol.HorizontalHeaderContentAlignment = newcol.TextAlignment == TextAlignment.Left ? HorizontalAlignment.Left
  1541. : newcol.TextAlignment == TextAlignment.Center ? HorizontalAlignment.Center
  1542. : HorizontalAlignment.Right;
  1543. ApplyFilterStyle(newcol, filtering, false);
  1544. var headstyle = new Style(typeof(GridHeaderCellControl));
  1545. headstyle.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  1546. headstyle.Setters.Add(new Setter(ForegroundProperty, new SolidColorBrush(Colors.Black)));
  1547. headstyle.Setters.Add(new Setter(FontSizeProperty, 12D));
  1548. newcol.HeaderStyle = headstyle;
  1549. var cellstyle = new Style();
  1550. if (Options.Contains(DynamicGridOption.DirectEdit))
  1551. {
  1552. if (prop.Editor is null || prop.Editor.Editable != Editable.Enabled)
  1553. {
  1554. cellstyle.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.WhiteSmoke)));
  1555. newcol.AllowEditing = false;
  1556. }
  1557. else
  1558. {
  1559. cellstyle.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.LightYellow)));
  1560. newcol.AllowEditing = true;
  1561. }
  1562. cellstyle.Setters.Add(new Setter(ForegroundProperty, new SolidColorBrush(Colors.Black)));
  1563. newcol.CellStyle = cellstyle;
  1564. }
  1565. else
  1566. {
  1567. cellstyle.Setters.Add(new Setter(BackgroundProperty, new Binding() { Path = new PropertyPath("."), Converter = CellBackgroundConverter, ConverterParameter = column.ColumnName }));
  1568. cellstyle.Setters.Add(new Setter(ForegroundProperty, new Binding() { Converter = CellForegroundConverter, ConverterParameter = column.ColumnName }));
  1569. cellstyle.Setters.Add(new Setter(FontSizeProperty, new Binding() { Converter = CellFontSizeConverter, ConverterParameter = column.ColumnName }));
  1570. cellstyle.Setters.Add(new Setter(FontStyleProperty, new Binding() { Converter = CellFontStyleConverter, ConverterParameter = column.ColumnName }));
  1571. cellstyle.Setters.Add(new Setter(FontWeightProperty, new Binding() { Converter = CellFontWeightConverter, ConverterParameter = column.ColumnName }));
  1572. newcol.CellStyle = cellstyle;
  1573. }
  1574. DataGrid.Columns.Add(newcol);
  1575. ColumnList.Add(column);
  1576. }
  1577. }
  1578. LoadActionColumns(DynamicActionColumnPosition.End);
  1579. if (Summaries.Any())
  1580. {
  1581. DataGrid.CellRenderers.Remove("TableSummary");
  1582. DataGrid.CellRenderers.Add("TableSummary", new TimeSpanAggregateRenderer());
  1583. DataGrid.TableSummaryRows.Add(new GridTableSummaryRow
  1584. {
  1585. ShowSummaryInRow = false,
  1586. Position = TableSummaryRowPosition.Bottom,
  1587. SummaryColumns = Summaries
  1588. });
  1589. }
  1590. DataGrid.Columns.Resume();
  1591. DataGrid.RefreshColumns();
  1592. foreach (var key in _filterpredicates.Keys.ToArray())
  1593. if (DataGrid.Columns.Any(x => string.Equals(x.MappingName, key)))
  1594. {
  1595. var predicates = Serialization.Deserialize<List<FilterPredicate>>(_filterpredicates[key]);
  1596. foreach (var predicate in predicates)
  1597. {
  1598. DataGrid.Columns[key].FilterPredicates.Add(predicate);
  1599. DataGrid.Columns[key].FilteredFrom = FilteredFrom.FilterRow;
  1600. }
  1601. }
  1602. else
  1603. {
  1604. _filterpredicates.Remove(key);
  1605. }
  1606. ResizeColumns(DataGrid, DataGrid.ActualWidth - 2, DataGrid.ActualHeight - 2);
  1607. }
  1608. private void ApplyFilterStyle(GridColumn column, bool filtering, bool isactioncolumn)
  1609. {
  1610. var filterstyle = new Style();
  1611. if (filtering)
  1612. {
  1613. filterstyle.Setters.Add(new Setter(BackgroundProperty, BaseDynamicGrid.FilterBackground));
  1614. column.ImmediateUpdateColumnFilter = true;
  1615. column.ColumnFilter = ColumnFilter.Value;
  1616. column.FilterRowCondition = FilterRowCondition.Contains;
  1617. column.FilterRowOptionsVisibility = Visibility.Collapsed;
  1618. column.AllowBlankFilters = true;
  1619. column.AllowSorting = isactioncolumn
  1620. ? false
  1621. : CanSort();
  1622. }
  1623. else
  1624. {
  1625. filterstyle.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  1626. filterstyle.Setters.Add(new Setter(IsEnabledProperty, false));
  1627. column.ColumnFilter = ColumnFilter.Value;
  1628. column.AllowFiltering = false;
  1629. column.AllowSorting = false;
  1630. column.FilterRowEditorType = "TextBox";
  1631. column.FilterRowOptionsVisibility = Visibility.Collapsed;
  1632. }
  1633. column.FilterRowCellStyle = filterstyle;
  1634. }
  1635. #endregion
  1636. #region Refresh / Reload
  1637. protected abstract void Reload(Filters<T> criteria, Columns<T> columns, ref SortOrder<T>? sort, Action<CoreTable?, Exception?> action);
  1638. protected virtual bool FilterRecord(CoreRow row)
  1639. {
  1640. var bOK = true;
  1641. foreach (var column in ActionColumns.Where(x => x.FilterRecord != null && x.SelectedFilters != null && x.SelectedFilters.Any()))
  1642. bOK = bOK && column.FilterRecord.Invoke(row, column.SelectedFilters);
  1643. if (bOK && OnFilterRecord is not null)
  1644. bOK = OnFilterRecord(row);
  1645. return bOK;
  1646. }
  1647. public override void Refresh(bool reloadcolumns, bool reloaddata)
  1648. {
  1649. if (bRefreshing)
  1650. return;
  1651. if (!DoBeforeRefresh())
  1652. return;
  1653. DataGrid.SelectionForegroundBrush = BaseDynamicGrid.SelectionForeground;
  1654. DataGrid.RowSelectionBrush = BaseDynamicGrid.SelectionBackground;
  1655. var cursor = UseWaitCursor ? new WaitCursor() : null;
  1656. Loading.Visibility = Visibility.Visible;
  1657. Loading.BeginAnimation(Label.OpacityProperty, LoadingFader);
  1658. bRefreshing = true;
  1659. // Yo, please don't remove this.
  1660. // 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
  1661. // 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(),
  1662. // and thus some mega problems (perhaps even exceptions within Syncfusion) were occurring, and this seems to fix it.
  1663. // I don't pretend to know why it works; this is probably the strangest problem I've ever come across.
  1664. if (reloadcolumns)
  1665. DataGrid.ItemsSource = null;
  1666. if (reloadcolumns)
  1667. ReloadColumns();
  1668. if (reloaddata)
  1669. {
  1670. _lookupcache.Clear();
  1671. var criteria = new Filters<T>();
  1672. var filter = DefineFilter();
  1673. if (filter != null)
  1674. criteria.Add(filter);
  1675. var columns = DataColumns();
  1676. var sort = LookupFactory.DefineSort<T>();
  1677. if (sort == null && IsSequenced)
  1678. sort = new SortOrder<T>("Sequence");
  1679. Reload(
  1680. criteria
  1681. , columns
  1682. , ref sort
  1683. , (table, exception) =>
  1684. {
  1685. if (exception != null)
  1686. {
  1687. Dispatcher.Invoke(() =>
  1688. {
  1689. MessageBox.Show(String.Format("Error: {0}", exception.Message));
  1690. });
  1691. }
  1692. else if (table is not null)
  1693. {
  1694. MasterData = table;
  1695. Dispatcher.Invoke(() =>
  1696. {
  1697. ProcessData(reloadcolumns, reloaddata);
  1698. DoAfterRefresh();
  1699. bRefreshing = false;
  1700. IsReady = true;
  1701. });
  1702. }
  1703. }
  1704. );
  1705. }
  1706. else
  1707. {
  1708. ProcessData(reloadcolumns, reloaddata);
  1709. DoAfterRefresh();
  1710. bRefreshing = false;
  1711. IsReady = true;
  1712. Loading.BeginAnimation(Label.OpacityProperty, null);
  1713. Loading.Visibility = Visibility.Collapsed;
  1714. }
  1715. if (cursor != null)
  1716. {
  1717. cursor.Dispose();
  1718. cursor = null;
  1719. }
  1720. bRefreshing = false;
  1721. }
  1722. protected override bool OnBeforeRefresh()
  1723. {
  1724. return true;
  1725. }
  1726. private bool DoBeforeRefresh()
  1727. {
  1728. var result = OnBeforeRefresh();
  1729. if (result)
  1730. {
  1731. var args = new BeforeRefreshEventArgs() { Cancel = false };
  1732. NotifyBeforeRefresh(args);
  1733. result = args.Cancel == false;
  1734. }
  1735. return result;
  1736. }
  1737. protected override void OnAfterRefresh()
  1738. {
  1739. }
  1740. protected void DoAfterRefresh()
  1741. {
  1742. OnAfterRefresh();
  1743. NotifyAfterRefresh(new AfterRefreshEventArgs());
  1744. }
  1745. public Columns<T> DataColumns()
  1746. {
  1747. var columns = new Columns<T>();
  1748. foreach (var column in VisibleColumns)
  1749. columns.Add(column.ColumnName);
  1750. foreach (var column in HiddenColumns)
  1751. columns.Add(column);
  1752. return columns;
  1753. }
  1754. private void ProcessData(bool reloadcolumns, bool reloaddata)
  1755. {
  1756. Data.Columns.Clear();
  1757. Data.Setters.Clear();
  1758. if (MasterData != null)
  1759. foreach (var column in MasterData.Columns)
  1760. Data.Columns.Add(column);
  1761. LoadData();
  1762. }
  1763. protected readonly Dictionary<CoreRow, CoreRow> _recordmap = new();
  1764. public override void UpdateRow<TRow, TType>(CoreRow row, Expression<Func<TRow, TType>> column, TType value, bool refresh = true)
  1765. {
  1766. row.Set(column, value);
  1767. _recordmap[row].Set(column, value);
  1768. if (refresh)
  1769. InvalidateRow(row);
  1770. }
  1771. public override void UpdateRow<TType>(CoreRow row, string column, TType value, bool refresh = true)
  1772. {
  1773. row.Set(column, value);
  1774. _recordmap[row].Set(column, value);
  1775. if (refresh)
  1776. InvalidateRow(row);
  1777. }
  1778. public void AddRow(CoreRow row)
  1779. {
  1780. if (MasterData is null) return;
  1781. var masterrow = MasterData.NewRow();
  1782. MasterData.LoadRow(masterrow, row);
  1783. Refresh(false, false);
  1784. }
  1785. public void AddRow(T data)
  1786. {
  1787. if (MasterData is null) return;
  1788. var masterrow = MasterData.NewRow();
  1789. MasterData.LoadRow(masterrow, data);
  1790. MasterData.Rows.Add(masterrow);
  1791. Refresh(false, false);
  1792. }
  1793. public void DeleteRow(CoreRow row)
  1794. {
  1795. if (MasterData is null) return;
  1796. var masterrow = _recordmap[row];
  1797. MasterData.Rows.Remove(masterrow);
  1798. Refresh(false, false);
  1799. }
  1800. private void FilterRows(CoreTable from, CoreTable into, Dictionary<CoreRow, CoreRow>? recordMap = null, Func<CoreRow, bool>? filter = null)
  1801. {
  1802. into.Rows.Clear();
  1803. recordMap?.Clear();
  1804. foreach (var row in from.Rows.ToArray())
  1805. if (FilterRecord(row) && filter?.Invoke(row) != false)
  1806. {
  1807. var newrow = into.NewRow();
  1808. for (var i = 0; i < into.Columns.Count; i++)
  1809. {
  1810. var value = i < row.Values.Count ? row.Values[i] : null;
  1811. if (into.Columns[i].DataType.IsNumeric())
  1812. value = into.Columns[i].DataType.IsDefault(value) ? null : value;
  1813. //else if (Data.Columns[i].DataType == typeof(String[]))
  1814. // value = String.Join("\n", value as String[]);
  1815. newrow.Values.Add(value);
  1816. }
  1817. //newrow.Values.AddRange(row.Values);
  1818. //if ((OnFilterRecord == null) || (OnFilterRecord(row)))
  1819. into.Rows.Add(newrow);
  1820. recordMap?.TryAdd(newrow, row);
  1821. }
  1822. }
  1823. private void LoadData()
  1824. {
  1825. ResetClipBuffer();
  1826. if (MasterData is null)
  1827. return;
  1828. FilterRows(MasterData, Data, _recordmap);
  1829. InvalidateGrid();
  1830. //ScrollBar.Value = _CurrentRow <= 0 ? 0 : _CurrentRow;
  1831. SelectedRows = Array.Empty<CoreRow>();
  1832. }
  1833. //IncrementalList<T> _data = null;
  1834. public void InvalidateRow(CoreRow row)
  1835. {
  1836. var rowdata = new List<object?>(row.Values);
  1837. foreach (var ac in ActionColumns)
  1838. rowdata.Add(ac.Data(row));
  1839. var datarow = DataGridItems.Rows[row.Index];
  1840. for (var i = 0; i < rowdata.Count; i++)
  1841. datarow[i] = rowdata[i] ?? DBNull.Value;
  1842. //datarow.ItemArray = rowdata.ToArray();
  1843. }
  1844. private void InvalidateGrid()
  1845. {
  1846. var defaults = new List<object?>();
  1847. var result = new DataTable();
  1848. foreach (var column in Data.Columns)
  1849. {
  1850. var colname = column.ColumnName.Replace('.', '_');
  1851. if (!result.Columns.Contains(colname))
  1852. {
  1853. result.Columns.Add(colname, column.DataType);
  1854. if (!Options.Contains(DynamicGridOption.DirectEdit))
  1855. defaults.Add(column.DataType.GetDefault());
  1856. }
  1857. }
  1858. for (var i = 0; i < ActionColumns.Count; i++)
  1859. result.Columns.Add(string.Format("ActionColumn{0}", i),
  1860. ActionColumns[i] is DynamicImageColumn
  1861. ? typeof(BitmapImage)
  1862. : typeof(String)
  1863. );
  1864. foreach (var row in Data.Rows)
  1865. {
  1866. var newrow = result.NewRow();
  1867. CoreRowToDataRow(newrow, row, defaults);
  1868. result.Rows.Add(newrow);
  1869. }
  1870. if (RowStyleSelector != null)
  1871. RowStyleSelector.Data = Data;
  1872. //int rowIndex = DataGrid.SelectionController.CurrentCellManager.CurrentRowColumnIndex.RowIndex;
  1873. //int columnIndex = DataGrid.SelectionController.CurrentCellManager.CurrentRowColumnIndex.ColumnIndex;
  1874. //int scrollRowIndex = DataGrid.GetVisualContainer().ScrollRows.LastBodyVisibleLineIndex;
  1875. DataGrid.ItemsSource = result;
  1876. //this.DataGrid.ScrollInView(new Syncfusion.UI.Xaml.ScrollAxis.RowColumnIndex(scrollRowIndex, columnIndex));
  1877. ResizeColumns(DataGrid, DataGrid.ActualWidth - 1, DataGrid.ActualHeight);
  1878. UpdateRecordCount();
  1879. Loading.BeginAnimation(Label.OpacityProperty, null);
  1880. Loading.Visibility = Visibility.Collapsed;
  1881. }
  1882. private void UpdateRecordCount()
  1883. {
  1884. var count = DataGrid.View != null ? DataGrid.View.Records.Count : Data.Rows.Count;
  1885. Count.Content = string.Format("{0} Records", count);
  1886. //Count.Visibility = _Options.Contains(DynamicGridOptions.RecordCount) && (count > 0) ? Visibility.Visible : Visibility.Collapsed;
  1887. }
  1888. public IList<CoreRow> FilteredRows()
  1889. {
  1890. var result = new List<CoreRow>();
  1891. var table = DataGridItems;
  1892. var rows = DataGrid.View.Records.Select(x => (x.Data as DataRowView)!).ToList();
  1893. foreach (var row in rows)
  1894. {
  1895. var iRow = table.Rows.IndexOf(row.Row);
  1896. result.Add(Data.Rows[iRow]);
  1897. }
  1898. return result;
  1899. }
  1900. // Doesn't appear to be used - removed 19/12/2022
  1901. /*private object?[] CreateRowValues(CoreRow row, List<object> defaults)
  1902. {
  1903. var rowdata = new List<object?>(row.Values);
  1904. foreach (var ac in ActionColumns)
  1905. rowdata.Add(ac.Image.Invoke(row));
  1906. var result = ProcessRow(rowdata, defaults);
  1907. return result.ToArray();
  1908. }*/
  1909. private void CoreRowToDataRow(DataRow newrow, CoreRow row, List<object?> defaults)
  1910. {
  1911. var rowdata = new List<object?>(row.Values);
  1912. foreach (var ac in ActionColumns)
  1913. rowdata.Add(ac.Data(row));
  1914. try
  1915. {
  1916. var data = ProcessRow(rowdata, defaults).ToArray();
  1917. newrow.ItemArray = data;
  1918. }
  1919. catch (Exception)
  1920. {
  1921. throw;
  1922. }
  1923. }
  1924. private static IEnumerable<object?> ProcessRow(List<object?> values, List<object?> defaults)
  1925. {
  1926. if (defaults == null || !defaults.Any())
  1927. return values;
  1928. var result = new List<object?>();
  1929. for (var i = 0; i < values.Count; i++)
  1930. {
  1931. var value = values[i];
  1932. var defaultvalue = i < defaults.Count ? defaults[i] : null;
  1933. result.Add(value == null || (value.Equals(defaultvalue) && !value.GetType().IsEnum) ? null : value);
  1934. }
  1935. return result;
  1936. }
  1937. //private void LoadMoreItems(uint count, int from)
  1938. //{
  1939. // var rows = Data.Rows.Skip(from).AsQueryable().Take(50);
  1940. // _data.LoadItems(rows.Select(x => x.ToObject<T>()));
  1941. // //var list = _orders.Skip(baseIndex).Take(50).ToList();
  1942. // //IncrementalItemsSource.LoadItems(list);
  1943. //}
  1944. public override void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  1945. {
  1946. if (string.IsNullOrWhiteSpace(value))
  1947. return;
  1948. DataGrid.Columns[column].FilterPredicates.Add(new FilterPredicate { FilterType = filtertype, FilterValue = value });
  1949. DataGrid.Columns[column].FilteredFrom = FilteredFrom.FilterRow;
  1950. }
  1951. #endregion
  1952. #region Item Manipulation
  1953. #region Load/Save/Delete
  1954. protected virtual T[] LoadItems(CoreRow[] rows)
  1955. {
  1956. var result = new List<T>();
  1957. foreach (var row in rows)
  1958. {
  1959. var index = Data.Rows.IndexOf(row);
  1960. result.Add(LoadItem(row));
  1961. }
  1962. return result.ToArray();
  1963. }
  1964. protected abstract T LoadItem(CoreRow row);
  1965. public abstract void SaveItem(T item);
  1966. public virtual void SaveItems(T[] items)
  1967. {
  1968. foreach (var item in items)
  1969. SaveItem(item);
  1970. }
  1971. protected virtual bool CanDeleteItems(params CoreRow[] rows)
  1972. {
  1973. return true;
  1974. }
  1975. protected abstract void DeleteItems(params CoreRow[] rows);
  1976. protected virtual void DoDelete()
  1977. {
  1978. var rows = SelectedRows.ToArray();
  1979. if (rows.Any())
  1980. if (CanDeleteItems(rows))
  1981. if (MessageBox.Show("Are you sure you wish to delete the selected records?", "Confirm Delete", MessageBoxButton.YesNo) ==
  1982. MessageBoxResult.Yes)
  1983. {
  1984. DeleteItems(rows);
  1985. SelectedRows = Array.Empty<CoreRow>();
  1986. OnChanged?.Invoke(this);
  1987. Refresh(false, true);
  1988. SelectItems(null);
  1989. }
  1990. }
  1991. private void Delete_Click(object sender, RoutedEventArgs e)
  1992. {
  1993. DoDelete();
  1994. }
  1995. #endregion
  1996. #region Edit
  1997. protected virtual void DoEdit()
  1998. {
  1999. if (!SelectedRows.Any())
  2000. return;
  2001. var sel = SelectedRows.ToArray();
  2002. if (AddEditClick(SelectedRows))
  2003. {
  2004. InvalidateGrid();
  2005. SelectedRows = sel;
  2006. SelectItems(SelectedRows);
  2007. }
  2008. }
  2009. private void Edit_Click(object sender, RoutedEventArgs e)
  2010. {
  2011. DoEdit();
  2012. }
  2013. /*private void MultiEdit_Click(object sender, RoutedEventArgs e)
  2014. {
  2015. using (new WaitCursor())
  2016. {
  2017. var criteria = new Filters<T>();
  2018. var columns = new Columns<T>();
  2019. columns.Add("ID");
  2020. var iprops = DatabaseSchema.Properties(typeof(T)).Where(x => x.Editor is not NullEditor);
  2021. foreach (var iprop in iprops)
  2022. columns.Add(iprop.Name);
  2023. var sort = LookupFactory.DefineSort<T>();
  2024. Reload(
  2025. criteria,
  2026. columns,
  2027. ref sort,
  2028. (table, exception) =>
  2029. {
  2030. if(table is not null)
  2031. {
  2032. Dispatcher.Invoke(() => { DirectEdit(table); });
  2033. }
  2034. else if(exception is not null)
  2035. {
  2036. Logger.Send(LogType.Error, "", $"Error in MultiEdit: {CoreUtils.FormatException(exception)}");
  2037. MessageBox.Show(exception.Message);
  2038. }
  2039. }
  2040. );
  2041. }
  2042. }*/
  2043. /*public override bool DirectEdit(CoreTable data)
  2044. {
  2045. var window = new DynamicEditWindow<T>();
  2046. window.OnCreateItem += () => CreateItem();
  2047. window.OnCustomiseColumns += (o, c) =>
  2048. {
  2049. ConfigureColumns(MasterColumns);
  2050. if (OnCustomiseColumns != null)
  2051. return OnCustomiseColumns(this, MasterColumns);
  2052. return MasterColumns;
  2053. };
  2054. window.OnGetEditor += c =>
  2055. {
  2056. var result = GetEditor(this, c)?.CloneEditor();
  2057. if (result == null)
  2058. return null;
  2059. OnCustomiseEditor?.Invoke(window, null, c, result);
  2060. return result;
  2061. };
  2062. window.OnGetSequence += c =>
  2063. {
  2064. decimal result = 0.0M;
  2065. var customprop = DatabaseSchema.Property(typeof(T), c.ColumnName);
  2066. if (customprop != null && customprop is CustomProperty)
  2067. {
  2068. result = customprop.Sequence;
  2069. }
  2070. else
  2071. {
  2072. var bits = c.ColumnName.Split('.');
  2073. for (var i = 0; i < bits.Length; i++)
  2074. {
  2075. var sProp = string.Join(".", bits.Take(bits.Length - i));
  2076. PropertyInfo? prop;
  2077. try
  2078. {
  2079. prop = CoreUtils.GetProperty(typeof(T), sProp);
  2080. }
  2081. catch (Exception e)
  2082. {
  2083. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2084. prop = null;
  2085. }
  2086. if (prop != null)
  2087. {
  2088. result = prop.GetSequence() + result / 1000.0M;
  2089. }
  2090. else
  2091. {
  2092. var cprop = DatabaseSchema.Property(typeof(T), sProp);
  2093. if (cprop != null)
  2094. result = cprop.Sequence;
  2095. else
  2096. result /= 1000.0M;
  2097. }
  2098. }
  2099. }
  2100. return result;
  2101. };
  2102. window.Load(data);
  2103. if (window.ShowDialog() == true)
  2104. {
  2105. SaveItems(window.Updates);
  2106. return true;
  2107. }
  2108. return false;
  2109. }*/
  2110. protected virtual void DoAdd(bool OpenEditorOnDirectEdit = false)
  2111. {
  2112. //CoreRow row = (SelectedRow > -1) && (SelectedRow < Data.Rows.Count) ? Data.Rows[this.SelectedRow] : null;
  2113. if (Options.Contains(DynamicGridOption.DirectEdit) && !OpenEditorOnDirectEdit)
  2114. {
  2115. if (!CanCreateItems())
  2116. return;
  2117. var item = CreateItem();
  2118. SaveItem(item);
  2119. var datarow = Data.NewRow();
  2120. ObjectToRow(item, datarow);
  2121. Data.Rows.Add(datarow);
  2122. var masterrow = MasterData.NewRow();
  2123. ObjectToRow(item, masterrow);
  2124. MasterData.Rows.Add(masterrow);
  2125. _recordmap[datarow] = masterrow;
  2126. InvalidateGrid();
  2127. SelectedRows = new[] { datarow };
  2128. OnChanged?.Invoke(this);
  2129. }
  2130. else if (AddEditClick(null))
  2131. {
  2132. Refresh(false, true);
  2133. OnChanged?.Invoke(this);
  2134. }
  2135. }
  2136. private void Add_Click(object sender, RoutedEventArgs e)
  2137. {
  2138. DoAdd();
  2139. }
  2140. public virtual DynamicEditorPages LoadEditorPages(T item)
  2141. {
  2142. DynamicEditorPages pages = new DynamicEditorPages();
  2143. DynamicGridUtils.LoadOneToManyPages(typeof(T), pages);
  2144. DynamicGridUtils.LoadEnclosedListPages(typeof(T), pages);
  2145. DynamicGridUtils.LoadManyToManyPages(typeof(T), pages);
  2146. DynamicGridUtils.LoadCustomEditorPages(typeof(T), pages);
  2147. foreach (var page in pages)
  2148. page.Ready = false;
  2149. return pages;
  2150. }
  2151. public virtual void LoadEditorButtons(T item, DynamicEditorButtons buttons)
  2152. {
  2153. buttons.Clear();
  2154. buttons.Add(
  2155. "",
  2156. Wpf.Resources.help.AsBitmapImage(),
  2157. item,
  2158. (f, i) =>
  2159. {
  2160. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + typeof(T).Name.SplitCamelCase().Replace(" ", "_"))
  2161. { UseShellExecute = true });
  2162. }
  2163. );
  2164. }
  2165. protected virtual void BeforeLoad(IDynamicEditorForm form)
  2166. {
  2167. form.BeforeLoad();
  2168. }
  2169. public override void InitialiseEditorForm(IDynamicEditorForm editor, T[] items, Func<Type, CoreTable>? pageDataHandler = null, bool preloadPages = false)
  2170. {
  2171. var pages = items.Length == 1 ? LoadEditorPages(items.First()) : new DynamicEditorPages();
  2172. var buttons = new DynamicEditorButtons();
  2173. if (items.Length == 1)
  2174. LoadEditorButtons(items.First(), buttons);
  2175. editor.Setup(items.Any() ? items.First().GetType() : typeof(T), pages, buttons, pageDataHandler, preloadPages);
  2176. editor.OnCustomiseColumns = (sender, columns) =>
  2177. {
  2178. columns.Clear();
  2179. columns.AddRange(MasterColumns);
  2180. ConfigureColumns(columns);
  2181. };
  2182. editor.OnDefineEditor = (o, c) =>
  2183. {
  2184. var result = GetEditor(o, c);
  2185. if (result != null)
  2186. result = result.CloneEditor();
  2187. return result;
  2188. };
  2189. editor.OnFormCustomiseEditor += (o, i, c, e) => OnCustomiseEditor?.Invoke(o, (T[])i, c, e);
  2190. editor.OnDefineFilter = (type) => { return DefineFilter(type, items); };
  2191. //editor.OnDefineFilter += (o, e) => { return DefineFilter(items, e); };
  2192. editor.OnDefineLookups = editor => DefineLookups(editor, items);
  2193. editor.OnEditorValueChanged += (s, n, v) => EditorValueChanged(editor, items, n, v);
  2194. editor.OnAfterEditorValueChanged += (g, n) => AfterEditorValueChanged(g, items, n);
  2195. editor.OnReconfigureEditors = g => ReconfigureEditors(g, items);
  2196. editor.OnValidateData += (o, i) => ValidateData(items);
  2197. editor.OnSelectPage += SelectPage;
  2198. editor.OnGetDocument = LoadDocument;
  2199. editor.OnFindDocument = FindDocument;
  2200. editor.OnSaveDocument = SaveDocument;
  2201. editor.OnSaveItem = (o, e) =>
  2202. {
  2203. try
  2204. {
  2205. using var Wait = new WaitCursor();
  2206. DoBeforeSave(editor, items);
  2207. if (items.Length == 1)
  2208. editor.UnloadEditorPages(false);
  2209. foreach (var item in items)
  2210. SaveItem(item);
  2211. if (items.Length == 1)
  2212. editor.UnloadEditorPages(true);
  2213. DoAfterSave(editor, items);
  2214. }
  2215. catch (Exception err)
  2216. {
  2217. MessageBox.Show(err.Message);
  2218. e.Cancel = true;
  2219. }
  2220. };
  2221. BeforeLoad(editor);
  2222. editor.Items = items;
  2223. AfterLoad(editor, items);
  2224. }
  2225. protected virtual void DoAfterSave(IDynamicEditorForm editor, T[] items)
  2226. {
  2227. OnAfterSave?.Invoke(editor, items);
  2228. }
  2229. protected virtual void DoBeforeSave(IDynamicEditorForm editor, T[] items)
  2230. {
  2231. OnBeforeSave?.Invoke(editor, items);
  2232. }
  2233. public override bool EditItems(T[] items, Func<Type, CoreTable>? PageDataHandler = null, bool PreloadPages = false)
  2234. {
  2235. DynamicEditorForm editor;
  2236. using (var cursor = new WaitCursor())
  2237. {
  2238. editor = new DynamicEditorForm();
  2239. editor.SetValue(Panel.ZIndexProperty, 999);
  2240. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  2241. }
  2242. return editor.ShowDialog() == true;
  2243. }
  2244. private Dictionary<String, object?> AfterEditorValueChanged(DynamicEditorGrid grid, T[] items, String columnnname)
  2245. {
  2246. var changes = new Dictionary<String, object?>();
  2247. OnAfterEditorValueChanged(grid, items, columnnname, changes);
  2248. return changes;
  2249. }
  2250. protected virtual void OnAfterEditorValueChanged(DynamicEditorGrid grid, T[] items, String columnnname, Dictionary<String, object?> changes)
  2251. {
  2252. }
  2253. protected virtual void ReconfigureEditors(DynamicEditorGrid grid, T[] items)
  2254. {
  2255. /*if (items.First() is IDimensioned dimensioned)
  2256. {
  2257. UpdateEditor(grid, x => x.Dimensions.Quantity, dimensioned.Dimensions.GetUnit().HasQuantity);
  2258. UpdateEditor(grid, x => x.Dimensions.Length, dimensioned.Dimensions.GetUnit().HasLength);
  2259. UpdateEditor(grid, x => x.Dimensions.Width, dimensioned.Dimensions.GetUnit().HasWidth);
  2260. UpdateEditor(grid, x => x.Dimensions.Height, dimensioned.Dimensions.GetUnit().HasHeight);
  2261. UpdateEditor(grid, x => x.Dimensions.Weight, dimensioned.Dimensions.GetUnit().HasWeight);
  2262. }*/
  2263. }
  2264. private string[]? ValidateData(T[] items)
  2265. {
  2266. var errors = new List<string>();
  2267. DoValidate(items, errors);
  2268. OnValidate?.Invoke(this, items, errors);
  2269. return errors.Any() ? errors.ToArray() : null;
  2270. }
  2271. protected virtual void DoValidate(T[] items, List<string> errors)
  2272. {
  2273. }
  2274. protected virtual void AfterLoad(IDynamicEditorForm editor, T[] items)
  2275. {
  2276. editor.AfterLoad();
  2277. }
  2278. protected virtual void SelectPage(object sender, BaseObject[]? items)
  2279. {
  2280. }
  2281. protected virtual Dictionary<string, object?> EditorValueChanged(IDynamicEditorForm editor, T[] items, string name, object value)
  2282. {
  2283. var result = DynamicGridUtils.UpdateEditorValue(items, name, value);
  2284. if (OnEditorValueChanged != null)
  2285. {
  2286. var newchanges = OnEditorValueChanged(editor, name, value);
  2287. foreach (var key in newchanges.Keys)
  2288. result[key] = newchanges[key];
  2289. }
  2290. return result;
  2291. }
  2292. private readonly Dictionary<Tuple<Type, Type>, Dictionary<object, object>> _lookupcache = new();
  2293. protected virtual void DefineLookups(ILookupEditorControl sender, T[] items)
  2294. {
  2295. if (sender.EditorDefinition is not ILookupEditor editor)
  2296. return;
  2297. var colname = sender.ColumnName;
  2298. //Logger.Send(LogType.Information, typeof(T).Name, "Into Define Lookups: " + colname);
  2299. Task.Run(() =>
  2300. {
  2301. try
  2302. {
  2303. var values = editor.Values(colname, items);
  2304. Dispatcher.Invoke(
  2305. () =>
  2306. {
  2307. try
  2308. {
  2309. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  2310. sender.LoadLookups(values);
  2311. }
  2312. catch (Exception e2)
  2313. {
  2314. Logger.Send(LogType.Information, typeof(T).Name,
  2315. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  2316. }
  2317. }
  2318. );
  2319. }
  2320. catch (Exception e)
  2321. {
  2322. Logger.Send(LogType.Information, typeof(T).Name, "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  2323. }
  2324. });
  2325. }
  2326. /// <summary>
  2327. /// Retrieves an editor to display for the given column of <paramref name="item"/>.
  2328. /// </summary>
  2329. /// <param name="item">The object being edited.</param>
  2330. /// <param name="column">The column of the editor.</param>
  2331. /// <returns>A new editor, or <see langword="null"/> if no editor defined and no sensible default exists.</returns>
  2332. protected virtual BaseEditor? GetEditor(object item, DynamicGridColumn column)
  2333. {
  2334. return column.Editor ?? CoreUtils.GetProperty(item.GetType(), column.ColumnName).GetEditor();
  2335. }
  2336. protected IFilter? DefineFilter(Type type, T[] items)
  2337. {
  2338. return LookupFactory.DefineFilter(items, type);
  2339. }
  2340. protected virtual void SetEditorValue(object item, string name, object value)
  2341. {
  2342. try
  2343. {
  2344. CoreUtils.SetPropertyValue(item, name, value);
  2345. }
  2346. catch (Exception e)
  2347. {
  2348. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2349. }
  2350. }
  2351. protected virtual object? GetEditorValue(object item, string name)
  2352. {
  2353. return CoreUtils.GetPropertyValue(item, name);
  2354. }
  2355. protected virtual Document? LoadDocument(Guid id)
  2356. {
  2357. return null;
  2358. }
  2359. protected virtual Document? FindDocument(string filename)
  2360. {
  2361. return null;
  2362. }
  2363. protected virtual void SaveDocument(Document document)
  2364. {
  2365. }
  2366. protected virtual bool CanCreateItems()
  2367. {
  2368. return true;
  2369. }
  2370. private bool AddEditClick(CoreRow[]? rows)
  2371. {
  2372. if (!IsEnabled || bRefreshing)
  2373. return false;
  2374. if (rows == null || !rows.Any())
  2375. {
  2376. if (!CanCreateItems())
  2377. return false;
  2378. var item = CreateItem();
  2379. // Yea, and this won't work, because we're actually usually showing the description of a linked item,
  2380. // Yea, and this won't work, because we're actually usually showing the description of a linked item,
  2381. // not the id of the link, and we need to set the ID to have it work properly :-(
  2382. //foreach (String key in VisualFilters.Keys)
  2383. // CoreUtils.SetPropertyValue(item, key, VisualFilters[key]);
  2384. if (EditItems(new[] { item }))
  2385. {
  2386. //_CurrentRow = Data.Rows.Count;
  2387. var row = Data.NewRow();
  2388. ObjectToRow(item, row);
  2389. Data.Rows.Add(row);
  2390. InvalidateGrid();
  2391. SelectedRows = new[] { row };
  2392. OnChanged?.Invoke(this);
  2393. return true;
  2394. }
  2395. return false;
  2396. }
  2397. var items = Array.Empty<T>();
  2398. using (new WaitCursor())
  2399. {
  2400. Stopwatch sw = new Stopwatch();
  2401. sw.Start();
  2402. items = LoadItems(rows);
  2403. //Logger.Send(LogType.Information, "DG:LoadItems", String.Format("Loaded Items: {0}ms", sw.ElapsedMilliseconds));
  2404. sw.Stop();
  2405. }
  2406. if (items.Any())
  2407. {
  2408. var sel = SelectedRows;
  2409. if (EditItems(items))
  2410. {
  2411. for (var i = 0; i < items.Length; i++)
  2412. ObjectToRow(items[i], rows[i]);
  2413. InvalidateGrid();
  2414. SelectedRows = sel;
  2415. OnChanged?.Invoke(this);
  2416. return true;
  2417. }
  2418. return false;
  2419. }
  2420. return false;
  2421. }
  2422. #endregion
  2423. #region Duplicate
  2424. protected virtual IEnumerable<T> LoadDuplicatorItems(CoreRow[] rows)
  2425. {
  2426. return LoadItems(rows);
  2427. }
  2428. private bool DoDuplicate(Button button, CoreRow[] rows)
  2429. {
  2430. if (!rows.Any())
  2431. {
  2432. MessageBox.Show("Please select at least one record to duplicate!");
  2433. return false;
  2434. }
  2435. /*var ids = ExtractValues(x => x.ID, Selection.Selected).ToArray();
  2436. if (!ids.Any())
  2437. {
  2438. MessageBox.Show("Please select at least one record to duplicate!");
  2439. return false;
  2440. }*/
  2441. var duplicator = (new T() as IDuplicatable)?.GetDuplicator();
  2442. if (duplicator is null)
  2443. {
  2444. MessageBox.Show($"Cannot duplicate {typeof(T)}");
  2445. return false;
  2446. }
  2447. duplicator.Duplicate(LoadDuplicatorItems(rows));// new Filter<T>(x => x.ID).InList(ids));
  2448. return true;
  2449. }
  2450. #endregion
  2451. protected virtual void ShowHelp(string slug)
  2452. {
  2453. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + slug) { UseShellExecute = true });
  2454. }
  2455. protected void ReloadForms<TTargetType, TTargetForm, TSourceForm>(IDynamicEditorForm editor, TTargetType item,
  2456. Expression<Func<TSourceForm, object?>> sourcekey, Guid sourceid)
  2457. where TTargetType : Entity, new()
  2458. where TTargetForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  2459. where TSourceForm : Entity, IRemotable, IPersistent, IDigitalForm<TTargetType>, new()
  2460. {
  2461. var type = typeof(IDynamicOneToManyGrid<,>).MakeGenericType(typeof(TTargetType), typeof(TTargetForm));
  2462. var page =
  2463. editor.Pages?.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(type)) as IDynamicOneToManyGrid<TTargetType, TTargetForm>;
  2464. if (page != null && item != null)
  2465. {
  2466. if (!page.Ready)
  2467. page.Load(item, null);
  2468. CoreTable table;
  2469. if (sourceid == Guid.Empty)
  2470. {
  2471. table = new CoreTable();
  2472. table.LoadColumns(typeof(TSourceForm));
  2473. }
  2474. else
  2475. {
  2476. table = new Client<TSourceForm>().Query(
  2477. new Filter<TSourceForm>(sourcekey).IsEqualTo(sourceid).And(x => x.Form.AppliesTo)
  2478. .IsEqualTo(typeof(TTargetType).EntityName().Split('.').Last())
  2479. );
  2480. }
  2481. var newforms = new List<TTargetForm>();
  2482. foreach (var row in table.Rows)
  2483. {
  2484. var sourceform = row.ToObject<TSourceForm>();
  2485. var targetform = new TTargetForm();
  2486. targetform.Form.ID = sourceform.Form.ID;
  2487. targetform.Form.Synchronise(sourceform.Form);
  2488. newforms.Add(targetform);
  2489. }
  2490. page.Items.Clear();
  2491. page.LoadItems(newforms.ToArray());
  2492. }
  2493. }
  2494. #region ClipBuffer
  2495. private Tuple<ClipAction, CoreRow[]>? ClipBuffer;
  2496. protected void ResetClipBuffer()
  2497. {
  2498. ClipBuffer = null;
  2499. }
  2500. protected void SetClipBuffer(ClipAction action, CoreRow[] rows)
  2501. {
  2502. ClipBuffer = new Tuple<ClipAction, CoreRow[]>(action, rows);
  2503. }
  2504. private void CutToClipBuffer()
  2505. {
  2506. SetClipBuffer(ClipAction.Cut, SelectedRows);
  2507. InvalidateGrid();
  2508. }
  2509. private void CopyToClipBuffer()
  2510. {
  2511. SetClipBuffer(ClipAction.Copy, SelectedRows);
  2512. InvalidateGrid();
  2513. }
  2514. private void PasteFromClipBuffer()
  2515. {
  2516. if (ClipBuffer == null)
  2517. return;
  2518. if (!IsSequenced)
  2519. return;
  2520. using (new WaitCursor())
  2521. {
  2522. var updates = ClipBuffer.Item2.Select(x => x.ToObject<T>()).ToList();
  2523. if (BeforePaste(updates, ClipBuffer.Item1))
  2524. {
  2525. var currow = SelectedRows.FirstOrDefault()
  2526. ?? Data.Rows.LastOrDefault();
  2527. var sequence = currow != null ? currow.Get<T, long>(c => ((ISequenceable)c).Sequence) : 0;
  2528. var postrows = Data.Rows.Where(r => !ClipBuffer.Item2.Contains(r) && r.Get<ISequenceable, long>(x => x.Sequence) >= sequence);
  2529. updates.AddRange(LoadItems(postrows.ToArray()));
  2530. foreach (var update in updates)
  2531. {
  2532. sequence++;
  2533. ((ISequenceable)update).Sequence = sequence;
  2534. }
  2535. }
  2536. if (updates.Any())
  2537. {
  2538. SaveItems(updates.ToArray());
  2539. Refresh(false, true);
  2540. }
  2541. }
  2542. }
  2543. protected virtual bool BeforePaste(IEnumerable<T> items, ClipAction action)
  2544. {
  2545. return true;
  2546. }
  2547. private void Cut_Click(object sender, RoutedEventArgs e)
  2548. {
  2549. CutToClipBuffer();
  2550. }
  2551. private void Copy_Click(object sender, RoutedEventArgs e)
  2552. {
  2553. CopyToClipBuffer();
  2554. }
  2555. private void Paste_Click(object sender, RoutedEventArgs e)
  2556. {
  2557. PasteFromClipBuffer();
  2558. }
  2559. #endregion
  2560. protected virtual void ObjectToRow(T obj, CoreRow row)
  2561. {
  2562. Data.LoadRow(row, obj);
  2563. }
  2564. #region Import / Export
  2565. protected virtual CoreTable LoadImportKeys(String[] fields)
  2566. {
  2567. var result = new CoreTable();
  2568. result.LoadColumns(new Columns<T>(fields));
  2569. return result;
  2570. }
  2571. protected virtual Guid GetImportID()
  2572. {
  2573. return Guid.Empty;
  2574. }
  2575. protected virtual bool CustomiseImportItem(T item)
  2576. {
  2577. if (IsSequenced)
  2578. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  2579. return true;
  2580. }
  2581. protected virtual string CustomiseImportFileName(string filename)
  2582. {
  2583. return filename;
  2584. }
  2585. protected virtual void DoImport()
  2586. {
  2587. var list = new DynamicImportList(
  2588. typeof(T),
  2589. GetImportID()
  2590. );
  2591. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  2592. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  2593. list.OnSave += (sender, entity) => SaveItem(entity as T);
  2594. list.OnLoad += (sender, type, fields, id) => LoadImportKeys(fields);
  2595. list.ShowDialog();
  2596. Refresh(false, true);
  2597. }
  2598. private void Import_Click(object sender, RoutedEventArgs e)
  2599. {
  2600. DoImport();
  2601. }
  2602. protected virtual void CustomiseExportColumns(List<string> columnnames)
  2603. {
  2604. }
  2605. protected virtual string CustomiseExportFileName(string filename)
  2606. {
  2607. return filename;
  2608. }
  2609. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  2610. {
  2611. }
  2612. protected virtual void ApplyExportFilter(CoreTable table, object data)
  2613. {
  2614. }
  2615. private static bool FilterByPredicate(CoreRow row, string column, FilterPredicate predicate)
  2616. {
  2617. var value = row[column];
  2618. var vStr = value?.ToString() ?? "";
  2619. var pValue = predicate.FilterValue;
  2620. var pStr = pValue?.ToString() ?? "";
  2621. return predicate.FilterType switch
  2622. {
  2623. FilterType.Contains => vStr.Contains(pStr),
  2624. FilterType.EndsWith => vStr.EndsWith(pStr),
  2625. FilterType.Equals => vStr.Equals(pStr),
  2626. FilterType.GreaterThan => vStr.CompareTo(pStr) > 0,
  2627. FilterType.GreaterThanOrEqual => vStr.CompareTo(pStr) >= 0,
  2628. FilterType.LessThan => vStr.CompareTo(pStr) < 0,
  2629. FilterType.LessThanOrEqual => vStr.CompareTo(pStr) <= 0,
  2630. FilterType.NotContains => !vStr.Contains(pStr),
  2631. FilterType.NotEndsWith => !vStr.EndsWith(pStr),
  2632. FilterType.NotEquals => !vStr.Equals(pStr),
  2633. FilterType.NotStartsWith => !vStr.StartsWith(pStr),
  2634. FilterType.StartsWith => vStr.StartsWith(pStr),
  2635. _ => true,
  2636. };
  2637. }
  2638. private List<Tuple<string, FilterPredicate>> GetFilterPredicates()
  2639. {
  2640. var list = new List<Tuple<string, FilterPredicate>>();
  2641. foreach (var column in DataGrid.Columns)
  2642. {
  2643. var colIndex = DataGrid.Columns.IndexOf(column);
  2644. var col = ColumnList[colIndex];
  2645. if (col is DynamicGridColumn gridColumn)
  2646. {
  2647. foreach (var predicate in column.FilterPredicates)
  2648. {
  2649. list.Add(new(gridColumn.ColumnName, predicate));
  2650. }
  2651. }
  2652. }
  2653. return list;
  2654. }
  2655. protected virtual void DoExport()
  2656. {
  2657. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  2658. CustomiseExportColumns(columnnames);
  2659. var form = new DynamicExportForm(typeof(T), columnnames);
  2660. if (form.ShowDialog() != true)
  2661. return;
  2662. var filters = new Filters<T>();
  2663. filters.Add(DefineFilter());
  2664. var predicates = GetFilterPredicates();
  2665. var visiblerows = GetVisibleRows();
  2666. CustomiseExportFilters(filters, visiblerows);
  2667. var columns = new Columns<T>(form.Fields);
  2668. var otherColumns = form.GetChildFields()
  2669. .Select(x => new Tuple<Type, IColumns>(
  2670. x.Key,
  2671. (Activator.CreateInstance(typeof(Columns<>).MakeGenericType(x.Key), new object[] { x.Value }) as IColumns)!))
  2672. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  2673. var reloadColumns = new Columns<T>();
  2674. foreach (var column in columns.ColumnNames())
  2675. {
  2676. reloadColumns.Add(column);
  2677. }
  2678. foreach (var column in HiddenColumns)
  2679. {
  2680. reloadColumns.Add(column);
  2681. }
  2682. foreach (var (column, _) in predicates)
  2683. {
  2684. reloadColumns.Add(column);
  2685. }
  2686. var sort = LookupFactory.DefineSort<T>();
  2687. Reload(filters, reloadColumns, ref sort, (data, err) => Dispatcher.Invoke(() =>
  2688. {
  2689. if (data is not null)
  2690. {
  2691. var newData = new CoreTable();
  2692. foreach (var column in columns.Items)
  2693. newData.Columns.Add(new CoreColumn { ColumnName = column.Property, DataType = column.Type });
  2694. FilterRows(data, newData, filter: (row) =>
  2695. {
  2696. foreach (var (column, predicate) in predicates)
  2697. {
  2698. if (!FilterByPredicate(row, column, predicate))
  2699. {
  2700. return false;
  2701. }
  2702. }
  2703. return true;
  2704. });
  2705. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), newData) };
  2706. list.AddRange(LoadExportTables(filters, otherColumns));
  2707. DoExportTables(list);
  2708. }
  2709. else if (err is not null)
  2710. {
  2711. Logger.Send(LogType.Error, "", $"Error in export: {CoreUtils.FormatException(err)}");
  2712. MessageBox.Show(err.Message);
  2713. }
  2714. }));
  2715. }
  2716. private void Export_Click(object sender, RoutedEventArgs e)
  2717. {
  2718. DoExport();
  2719. }
  2720. /// <summary>
  2721. /// Loads the child tables for an export, based on the filter of the parent table.
  2722. /// </summary>
  2723. /// <remarks>
  2724. /// If not overriden, defaults to creating empty tables with no records.
  2725. /// </remarks>
  2726. /// <param name="filter">Filter for the parent table.</param>
  2727. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  2728. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  2729. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  2730. {
  2731. return tableColumns.Select(x =>
  2732. {
  2733. var table = new CoreTable();
  2734. table.LoadColumns(x.Item2);
  2735. return new Tuple<Type?, CoreTable>(x.Item1, table);
  2736. });
  2737. }
  2738. private void DoExportTables(List<Tuple<Type?, CoreTable>> data)
  2739. {
  2740. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  2741. ExcelExporter.DoExport(data, filename);
  2742. }
  2743. #endregion
  2744. public void ScrollIntoView(CoreRow row)
  2745. {
  2746. DataGrid.ScrollInView(new RowColumnIndex(row.Index + 1, 0));
  2747. }
  2748. #endregion
  2749. #region Custom Buttons
  2750. private Button CreateButton(BitmapImage? image = null, string? text = null, string? tooltip = null)
  2751. {
  2752. var button = new Button();
  2753. button.SetValue(BorderBrushProperty, new SolidColorBrush(Colors.Gray));
  2754. button.SetValue(BorderThicknessProperty, new Thickness(0.75));
  2755. button.Height = 30;
  2756. UpdateButton(button, image, text, tooltip);
  2757. return button;
  2758. }
  2759. protected void UpdateButton(Button button, BitmapImage? image, string? text, string? tooltip = null)
  2760. {
  2761. var stackPnl = new StackPanel();
  2762. stackPnl.Orientation = Orientation.Horizontal;
  2763. //stackPnl.Margin = new Thickness(2);
  2764. if (image != null)
  2765. {
  2766. var img = new Image();
  2767. img.Source = image;
  2768. img.Margin = new Thickness(2);
  2769. img.ToolTip = tooltip;
  2770. stackPnl.Children.Add(img);
  2771. }
  2772. if (!string.IsNullOrEmpty(text))
  2773. {
  2774. button.MaxWidth = double.MaxValue;
  2775. var lbl = new Label();
  2776. lbl.Content = text;
  2777. lbl.VerticalAlignment = VerticalAlignment.Stretch;
  2778. lbl.VerticalContentAlignment = VerticalAlignment.Center;
  2779. lbl.Margin = new Thickness(2, 0, 5, 0);
  2780. lbl.ToolTip = ToolTip;
  2781. stackPnl.Children.Add(lbl);
  2782. }
  2783. else
  2784. button.MaxWidth = 30;
  2785. button.Content = stackPnl;
  2786. button.ToolTip = tooltip;
  2787. }
  2788. private bool bFirstButtonAdded = true;
  2789. private bool AnyButtonsVisible()
  2790. {
  2791. if (Add.Visibility != Visibility.Collapsed)
  2792. return true;
  2793. if (Edit.Visibility != Visibility.Collapsed)
  2794. return true;
  2795. /*if (MultiEdit.Visibility != Visibility.Collapsed)
  2796. return true;*/
  2797. if (Export.Visibility != Visibility.Collapsed)
  2798. return true;
  2799. return false;
  2800. }
  2801. public override Button AddButton(string caption, BitmapImage? image, string? tooltip, Func<Button, CoreRow[], bool> action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  2802. {
  2803. var button = CreateButton(image, caption, tooltip);
  2804. button.Margin = position == DynamicGridButtonPosition.Right
  2805. ? new Thickness(2, 2, 0, 0)
  2806. : bFirstButtonAdded && AnyButtonsVisible()
  2807. ? new Thickness(0, 2, 0, 0)
  2808. : new Thickness(0, 2, 2, 0);
  2809. button.Padding = !String.IsNullOrWhiteSpace(caption) ? new Thickness(5, 1, 5, 1) : new Thickness(1);
  2810. button.Tag = action;
  2811. button.Click += Button_Click;
  2812. if (position == DynamicGridButtonPosition.Right)
  2813. RightButtonStack.Children.Add(button);
  2814. else
  2815. LeftButtonStack.Children.Add(button);
  2816. bFirstButtonAdded = false;
  2817. return button;
  2818. }
  2819. public Button AddButton(string caption, BitmapImage? image, Func<Button, CoreRow[], bool> action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  2820. {
  2821. var result = AddButton(caption, image, null, action, position);
  2822. return result;
  2823. }
  2824. private void Button_Click(object sender, RoutedEventArgs e)
  2825. {
  2826. var button = (Button)sender;
  2827. var action = (Func<Button, CoreRow[], bool>)button.Tag;
  2828. //CoreRow row = (CurrentRow > -1) && (CurrentRow < Data.Rows.Count) ? Data.Rows[this.CurrentRow] : null;
  2829. if (action.Invoke(button, SelectedRows))
  2830. Refresh(false, true);
  2831. }
  2832. #endregion
  2833. #region Header Actions
  2834. private void SelectColumnsClick(object sender, RoutedEventArgs e)
  2835. {
  2836. var editor = new DynamicGridColumnsEditor(typeof(T));
  2837. editor.DirectEdit = Options.Contains(DynamicGridOption.DirectEdit);
  2838. editor.Columns.AddRange(VisibleColumns);
  2839. if (editor.ShowDialog().Equals(true))
  2840. {
  2841. VisibleColumns.Clear();
  2842. VisibleColumns.AddRange(editor.Columns);
  2843. SaveColumns(VisibleColumns);
  2844. //OnSaveColumns?.Invoke(this, editor.Columns);
  2845. Refresh(true, true);
  2846. }
  2847. }
  2848. #endregion
  2849. #region Drag + Drop
  2850. private static string DragFormat => typeof(DynamicGridDragFormat).FullName ?? "";
  2851. protected virtual void OnDragEnd(Type entity, CoreTable table)
  2852. {
  2853. }
  2854. private void DataGrid_Drop(object sender, DragEventArgs e)
  2855. {
  2856. if (e.Data.GetDataPresent(DragFormat))
  2857. {
  2858. var data = e.Data.GetData(DragFormat) as DynamicGridDragFormat;
  2859. if (data is not null)
  2860. {
  2861. var table = new CoreTable();
  2862. foreach (var column in data.Table.Columns)
  2863. {
  2864. if (column is DataColumn dataColumn)
  2865. {
  2866. table.Columns.Add(new CoreColumn { ColumnName = dataColumn.ColumnName, DataType = dataColumn.DataType });
  2867. }
  2868. }
  2869. foreach (var row in data.Table.Rows)
  2870. {
  2871. if (row is DataRow dataRow)
  2872. {
  2873. var coreRow = table.NewRow();
  2874. coreRow.LoadValues(dataRow.ItemArray);
  2875. table.Rows.Add(coreRow);
  2876. }
  2877. }
  2878. OnDragEnd(data.Entity, table);
  2879. }
  2880. }
  2881. }
  2882. protected void DragTable(Type entity, CoreTable table)
  2883. {
  2884. var data = new DataObject();
  2885. data.SetData(DragFormat, new DynamicGridDragFormat(table.ToDataTable(), entity));
  2886. DragDrop.DoDragDrop(this, data, DragDropEffects.All);
  2887. }
  2888. protected virtual void OnRowsDragStart(CoreRow[] rows)
  2889. {
  2890. var table = new CoreTable();
  2891. table.LoadColumns(Data.Columns);
  2892. table.LoadRows(rows);
  2893. DragTable(typeof(T), table);
  2894. }
  2895. private void RowDragDropController_DragStart(object? sender, GridRowDragStartEventArgs e)
  2896. {
  2897. var rows = new List<CoreRow>();
  2898. foreach (var record in e.DraggingRecords)
  2899. {
  2900. var rowIndex = DataGrid.ResolveToRowIndex(record);
  2901. rows.Add(GetRowFromIndex(rowIndex));
  2902. }
  2903. var rowArr = rows.ToArray();
  2904. OnRowsDragStart(rowArr);
  2905. e.Handled = true;
  2906. }
  2907. #endregion
  2908. /* Removed as appears unused; removed as of 19/12/2022
  2909. #region CellRendering
  2910. private void PopulateDynamicActionCell(DynamicActionColumn column, int rowIndex, int columnIndex, GridStyleInfo style)
  2911. {
  2912. style.CellType = "ImageCell";
  2913. var bi = column.Image?.Invoke(rowIndex < 0 ? null : Data.Rows[rowIndex]);
  2914. if (bi != null)
  2915. {
  2916. style.CellValue = bi;
  2917. style.BorderMargins = new CellMarginsInfo(4.0F);
  2918. }
  2919. }
  2920. //bool rowstylehelperinitialised = false;
  2921. //protected virtual void ProcessCellStyle(CoreRow row, int column, GridStyleInfo style)
  2922. //{
  2923. // if (!rowstylehelperinitialised)
  2924. // {
  2925. // Script stylescript = new Client<Script>().Load(new Filter<Script>(x => x.Section).IsEqualTo(typeof(T).EntityName()).And(x => x.ScriptType).IsEqualTo(ScriptType.RowStyle)).FirstOrDefault(); ;
  2926. // if (stylescript != null)
  2927. // {
  2928. // rowstylehelper = new ScriptDocument(stylescript.Code);
  2929. // if (!rowstylehelper.Compile())
  2930. // {
  2931. // MessageBox.Show("Unable to Load Row Style Helper!\r\n\r\n" + rowstylehelper.Result);
  2932. // rowstylehelper = null;
  2933. // }
  2934. // }
  2935. // rowstylehelperinitialised = true;
  2936. // }
  2937. // if (rowstylehelper != null)
  2938. // {
  2939. // try
  2940. // {
  2941. // rowstylehelper.SetValue("Row", row);
  2942. // rowstylehelper.SetValue("Column", Data.Columns[column].ColumnName);
  2943. // rowstylehelper.SetValue("Background", style.Background);
  2944. // rowstylehelper.SetValue("Foreground", style.Foreground);
  2945. // rowstylehelper.SetValue("Style", style.Font.FontStyle);
  2946. // rowstylehelper.SetValue("Weight", style.Font.FontWeight);
  2947. // if (rowstylehelper.Execute())
  2948. // {
  2949. // style.Background = (System.Windows.Media.Brush)rowstylehelper.GetValue("Background");
  2950. // style.Foreground = (System.Windows.Media.Brush)rowstylehelper.GetValue("Foreground");
  2951. // style.Font.FontStyle = (FontStyle)rowstylehelper.GetValue("Style");
  2952. // style.Font.FontWeight = (FontWeight)rowstylehelper.GetValue("Weight");
  2953. // }
  2954. // }
  2955. // catch (Exception e)
  2956. // {
  2957. // //MessageBox.Show("Unable to Invoke Row Style Helper!\r\n\r\n" + e.Message);
  2958. // }
  2959. // }
  2960. //}
  2961. private readonly Dictionary<string, BaseEditor> editorcache = new();
  2962. private void PopulateDataCell(int rowIndex, int columnIndex, GridStyleInfo style)
  2963. {
  2964. if (columnIndex > -1 && columnIndex < ColumnList.Count)
  2965. {
  2966. var o = ColumnList[columnIndex];
  2967. if (o is DynamicActionColumn)
  2968. {
  2969. PopulateDynamicActionCell((DynamicActionColumn)o, rowIndex, columnIndex, style);
  2970. }
  2971. else
  2972. {
  2973. var dgc = (DynamicGridColumn)o;
  2974. var dc = Data.Columns.FirstOrDefault(x => x.ColumnName.Equals(dgc.ColumnName));
  2975. var fmt = string.IsNullOrWhiteSpace(dgc.Format) ? "{0}" : "{0:" + dgc.Format.Replace("\\:", ":").Replace(":", "\\:") + "}";
  2976. object? val = null;
  2977. if (rowIndex < Data.Rows.Count)
  2978. val = Data.Rows[rowIndex][dgc.ColumnName];
  2979. if (val != null && dgc.Lookups.ContainsKey(val))
  2980. val = dgc.Lookups[val];
  2981. if (dc != null)
  2982. {
  2983. if(!editorcache.TryGetValue(dc.ColumnName, out var editor))
  2984. {
  2985. var prop = DatabaseSchema.Property(typeof(T), dc.ColumnName);
  2986. if (prop != null)
  2987. editor = prop.Editor;
  2988. else
  2989. editor = EditorUtils.GetEditor(dc.DataType) ?? new NullEditor();
  2990. editorcache[dc.ColumnName] = editor;
  2991. }
  2992. if (editor is CheckBoxEditor)
  2993. {
  2994. style.CellType = "CheckBox";
  2995. style.CellValue = val;
  2996. style.HorizontalAlignment = dc == null ? HorizontalAlignment.Left : dgc.HorizontalAlignment(dc.DataType);
  2997. style.VerticalAlignment = dgc.VerticalAlignment();
  2998. style.TextMargins = new CellMarginsInfo(2.0F);
  2999. }
  3000. else if (editor is ColorEditor)
  3001. {
  3002. style.CellType = "ImageCell";
  3003. var str = val?.ToString();
  3004. if (!string.IsNullOrWhiteSpace(str))
  3005. {
  3006. var color = ColorTranslator.FromHtml(str); // System.Drawing.Color.FromName(val.ToString());
  3007. var bitmap = ImageUtils.BitmapFromColor(color, (int)style.GridModel.ColumnWidths[columnIndex],
  3008. (int)style.GridModel.RowHeights[rowIndex], Color.Black);
  3009. //bitmap.Save(val.ToString().Replace("#","") + ".png");
  3010. style.CellValue = bitmap.AsBitmapImage(false);
  3011. style.BorderMargins = new CellMarginsInfo(4.0F);
  3012. }
  3013. }
  3014. else
  3015. {
  3016. string value;
  3017. try
  3018. {
  3019. if(val is null)
  3020. {
  3021. value = "";
  3022. }
  3023. else if (val.GetType().IsEnum)
  3024. {
  3025. value = val.ToString()!;
  3026. }
  3027. else if (val.GetType().IsDefault(val))
  3028. {
  3029. value = "";
  3030. }
  3031. else
  3032. {
  3033. value = string.Format(new TimeSpanFormatter(), fmt, val);
  3034. }
  3035. }
  3036. catch (Exception e)
  3037. {
  3038. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  3039. value = val?.ToString() ?? "";
  3040. }
  3041. if (editor is PasswordEditor)
  3042. style.CellValue = "".PadLeft(value.Length, '●');
  3043. else
  3044. style.CellValue = value;
  3045. style.HorizontalAlignment = dc == null ? HorizontalAlignment.Left : dgc.HorizontalAlignment(dc.DataType);
  3046. style.VerticalAlignment = dgc.VerticalAlignment();
  3047. style.CellType = "Static";
  3048. style.TextMargins = new CellMarginsInfo(2.0F);
  3049. }
  3050. }
  3051. }
  3052. }
  3053. }
  3054. private void PopulateHeaderCell(int columnIndex, GridStyleInfo style)
  3055. {
  3056. if (columnIndex > -1 && columnIndex < ColumnList.Count)
  3057. {
  3058. var o = ColumnList[columnIndex];
  3059. if (o is DynamicActionColumn)
  3060. {
  3061. PopulateDynamicActionCell((DynamicActionColumn)o, -1, columnIndex, style);
  3062. }
  3063. else
  3064. {
  3065. var dgc = (DynamicGridColumn)o;
  3066. if (Data != null)
  3067. {
  3068. var dc = Data.Columns.FirstOrDefault(x => x.ColumnName.Equals(dgc.ColumnName));
  3069. style.HorizontalAlignment = dc != null ? dgc.HorizontalAlignment(dc.DataType) : HorizontalAlignment.Left;
  3070. }
  3071. style.CellValue = string.IsNullOrWhiteSpace(dgc.Caption) ? dgc.ColumnName : dgc.Caption;
  3072. style.VerticalAlignment = dgc.VerticalAlignment();
  3073. style.CellType = "Static";
  3074. style.TextMargins = new CellMarginsInfo(2.0F);
  3075. }
  3076. }
  3077. }
  3078. #endregion
  3079. */
  3080. /* Removed as appears unused; removed as of 19/12/2022
  3081. #region Drag and Drop
  3082. private Point startpoint;
  3083. private void CheckPreviewMouseDown(object sender, MouseButtonEventArgs e)
  3084. {
  3085. if (!Options.Contains(DynamicGridOption.DragSource))
  3086. return;
  3087. if (e.LeftButton == MouseButtonState.Pressed)
  3088. {
  3089. Logger.Send(LogType.Information, GetType().EntityName(), "Initiating Start Point");
  3090. startpoint = e.GetPosition(DataGrid);
  3091. }
  3092. }
  3093. //private void CheckPreviewMouseMove(object sender, MouseEventArgs e)
  3094. //{
  3095. // Logger.Send(LogType.Information, this.GetType().EntityName(), String.Format("Checking Mouse Move: StartPoint = {0},{1}", startpoint.X, startpoint.Y));
  3096. // if (!_Options.Contains(DynamicGridOptions.DragSource))
  3097. // return;
  3098. // Vector diff = startpoint - e.GetPosition(null);
  3099. // 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));
  3100. // if ( (startpoint.X != 0) && (startpoint.Y != 0))
  3101. // {
  3102. // if ((Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance) || (Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
  3103. // {
  3104. // Logger.Send(LogType.Information, this.GetType().EntityName(), "Starting Drag Drop Operation");
  3105. // DataObject dragData = new DataObject(typeof(T).EntityName(), SelectedRows);
  3106. // DragDrop.DoDragDrop(DataGrid, dragData, DragDropEffects.Copy);
  3107. // }
  3108. // }
  3109. //}
  3110. private void CheckPreviewMouseUp(object sender, MouseButtonEventArgs e)
  3111. {
  3112. if (!Options.Contains(DynamicGridOption.DragSource))
  3113. return;
  3114. Logger.Send(LogType.Information, GetType().EntityName(), "Clearing Start Point");
  3115. startpoint = new Point();
  3116. }
  3117. #endregion
  3118. */
  3119. }
  3120. }