DynamicGrid.cs 158 KB

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