DynamicGrid.cs 156 KB

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