DynamicGrid.cs 147 KB

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