DynamicGrid.cs 147 KB

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