DynamicGrid.cs 143 KB

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