DynamicGrid.cs 131 KB

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