DynamicGrid.cs 143 KB

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