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