DynamicGrid.cs 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275
  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. FilterRows();
  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()
  1624. {
  1625. ResetClipBuffer();
  1626. Data.Rows.Clear();
  1627. _recordmap.Clear();
  1628. if (MasterData is null)
  1629. return;
  1630. foreach (var row in MasterData.Rows)
  1631. if (FilterRecord(row))
  1632. {
  1633. var newrow = Data.NewRow();
  1634. for (var i = 0; i < Data.Columns.Count; i++)
  1635. {
  1636. var value = i < row.Values.Count ? row.Values[i] : null;
  1637. if (Data.Columns[i].DataType.IsNumeric())
  1638. value = Data.Columns[i].DataType.IsDefault(value) ? null : value;
  1639. //else if (Data.Columns[i].DataType == typeof(String[]))
  1640. // value = String.Join("\n", value as String[]);
  1641. newrow.Values.Add(value);
  1642. }
  1643. //newrow.Values.AddRange(row.Values);
  1644. //if ((OnFilterRecord == null) || (OnFilterRecord(row)))
  1645. Data.Rows.Add(newrow);
  1646. _recordmap[newrow] = row;
  1647. }
  1648. InvalidateGrid();
  1649. //ScrollBar.Value = _CurrentRow <= 0 ? 0 : _CurrentRow;
  1650. SelectedRows = new CoreRow[] { };
  1651. }
  1652. //IncrementalList<T> _data = null;
  1653. private void InvalidateRow(CoreRow row)
  1654. {
  1655. var rowdata = new List<object?>(row.Values);
  1656. foreach (var ac in ActionColumns)
  1657. rowdata.Add(ac.Image.Invoke(row));
  1658. var datarow = DataGridItems.Rows[row.Index];
  1659. for (var i = 0; i < rowdata.Count; i++)
  1660. datarow[i] = rowdata[i] ?? DBNull.Value;
  1661. //datarow.ItemArray = rowdata.ToArray();
  1662. }
  1663. private void InvalidateGrid()
  1664. {
  1665. var defaults = new List<object?>();
  1666. var result = new DataTable();
  1667. foreach (var column in Data.Columns)
  1668. {
  1669. var colname = column.ColumnName.Replace('.', '_');
  1670. if (!result.Columns.Contains(colname))
  1671. {
  1672. result.Columns.Add(colname, column.DataType);
  1673. if (!Options.Contains(DynamicGridOption.DirectEdit))
  1674. defaults.Add(column.DataType.GetDefault());
  1675. }
  1676. }
  1677. for (var i = 0; i < ActionColumns.Count; i++)
  1678. result.Columns.Add(string.Format("ActionColumn{0}", i), typeof(BitmapImage));
  1679. foreach (var row in Data.Rows)
  1680. {
  1681. var newrow = result.NewRow();
  1682. CoreRowToDataRow(newrow, row, defaults);
  1683. result.Rows.Add(newrow);
  1684. }
  1685. if (StyleSelector != null)
  1686. StyleSelector.Data = Data;
  1687. //int rowIndex = DataGrid.SelectionController.CurrentCellManager.CurrentRowColumnIndex.RowIndex;
  1688. //int columnIndex = DataGrid.SelectionController.CurrentCellManager.CurrentRowColumnIndex.ColumnIndex;
  1689. //int scrollRowIndex = DataGrid.GetVisualContainer().ScrollRows.LastBodyVisibleLineIndex;
  1690. DataGrid.ItemsSource = result;
  1691. //this.DataGrid.ScrollInView(new Syncfusion.UI.Xaml.ScrollAxis.RowColumnIndex(scrollRowIndex, columnIndex));
  1692. ResizeColumns(DataGrid, DataGrid.ActualWidth - 1, DataGrid.ActualHeight);
  1693. UpdateRecordCount();
  1694. Loading.Visibility = Visibility.Collapsed;
  1695. var timer = (DispatcherTimer)Loading.Tag;
  1696. timer.IsEnabled = false;
  1697. }
  1698. private void UpdateRecordCount()
  1699. {
  1700. var count = DataGrid.View != null ? DataGrid.View.Records.Count : Data.Rows.Count;
  1701. Count.Content = string.Format("{0} Records", count);
  1702. //Count.Visibility = _Options.Contains(DynamicGridOptions.RecordCount) && (count > 0) ? Visibility.Visible : Visibility.Collapsed;
  1703. }
  1704. public IList<CoreRow> FilteredRows()
  1705. {
  1706. var result = new List<CoreRow>();
  1707. var table = DataGridItems;
  1708. var rows = DataGrid.View.Records.Select(x => (x.Data as DataRowView)!).ToList();
  1709. foreach (var row in rows)
  1710. {
  1711. var iRow = table.Rows.IndexOf(row.Row);
  1712. result.Add(Data.Rows[iRow]);
  1713. }
  1714. return result;
  1715. }
  1716. // Doesn't appear to be used - removed 19/12/2022
  1717. /*private object?[] CreateRowValues(CoreRow row, List<object> defaults)
  1718. {
  1719. var rowdata = new List<object?>(row.Values);
  1720. foreach (var ac in ActionColumns)
  1721. rowdata.Add(ac.Image.Invoke(row));
  1722. var result = ProcessRow(rowdata, defaults);
  1723. return result.ToArray();
  1724. }*/
  1725. private void CoreRowToDataRow(DataRow newrow, CoreRow row, List<object?> defaults)
  1726. {
  1727. var rowdata = new List<object?>(row.Values);
  1728. foreach (var ac in ActionColumns)
  1729. rowdata.Add(ac.Image.Invoke(row));
  1730. try
  1731. {
  1732. var data = ProcessRow(rowdata, defaults).ToArray();
  1733. newrow.ItemArray = data;
  1734. }
  1735. catch (Exception)
  1736. {
  1737. throw;
  1738. }
  1739. }
  1740. private static IEnumerable<object?> ProcessRow(List<object?> values, List<object?> defaults)
  1741. {
  1742. if (defaults == null || !defaults.Any())
  1743. return values;
  1744. var result = new List<object?>();
  1745. for (var i = 0; i < values.Count; i++)
  1746. {
  1747. var value = values[i];
  1748. var defaultvalue = i < defaults.Count ? defaults[i] : null;
  1749. result.Add(value == null || (value.Equals(defaultvalue) && !value.GetType().IsEnum) ? null : value);
  1750. }
  1751. return result;
  1752. }
  1753. //private void LoadMoreItems(uint count, int from)
  1754. //{
  1755. // var rows = Data.Rows.Skip(from).AsQueryable().Take(50);
  1756. // _data.LoadItems(rows.Select(x => x.ToObject<T>()));
  1757. // //var list = _orders.Skip(baseIndex).Take(50).ToList();
  1758. // //IncrementalItemsSource.LoadItems(list);
  1759. //}
  1760. public override void AddVisualFilter(string column, string value)
  1761. {
  1762. if (!string.IsNullOrWhiteSpace(value))
  1763. {
  1764. DataGrid.Columns[column].FilterPredicates.Add(new FilterPredicate { FilterType = FilterType.Contains, FilterValue = value });
  1765. }
  1766. }
  1767. #endregion
  1768. #region Item Manipulation
  1769. #region Load/Save/Delete
  1770. protected virtual T[] LoadItems(CoreRow[] rows)
  1771. {
  1772. var result = new List<T>();
  1773. foreach (var row in rows)
  1774. {
  1775. var index = Data.Rows.IndexOf(row);
  1776. result.Add(LoadItem(row));
  1777. }
  1778. return result.ToArray();
  1779. }
  1780. protected abstract T LoadItem(CoreRow row);
  1781. protected abstract void SaveItem(T item);
  1782. protected virtual void SaveItems(T[] items)
  1783. {
  1784. foreach (var item in items)
  1785. SaveItem(item);
  1786. }
  1787. protected virtual bool CanDeleteItems(params CoreRow[] rows)
  1788. {
  1789. return true;
  1790. }
  1791. protected abstract void DeleteItems(params CoreRow[] rows);
  1792. protected virtual void DoDelete()
  1793. {
  1794. var rows = SelectedRows.ToArray();
  1795. if (rows.Any())
  1796. if (CanDeleteItems(rows))
  1797. if (MessageBox.Show("Are you sure you wish to delete the selected records?", "Confirm Delete", MessageBoxButton.YesNo) ==
  1798. MessageBoxResult.Yes)
  1799. {
  1800. DeleteItems(rows);
  1801. SelectedRows = Array.Empty<CoreRow>();
  1802. OnChanged?.Invoke(this);
  1803. Refresh(false, true);
  1804. SelectItems(null);
  1805. }
  1806. }
  1807. private void Delete_Click(object sender, RoutedEventArgs e)
  1808. {
  1809. DoDelete();
  1810. }
  1811. #endregion
  1812. #region Edit
  1813. protected virtual void DoEdit()
  1814. {
  1815. if (!SelectedRows.Any())
  1816. return;
  1817. var sel = SelectedRows.ToArray();
  1818. if (AddEditClick(SelectedRows))
  1819. {
  1820. InvalidateGrid();
  1821. SelectedRows = sel;
  1822. SelectItems(SelectedRows);
  1823. }
  1824. }
  1825. private void Edit_Click(object sender, RoutedEventArgs e)
  1826. {
  1827. DoEdit();
  1828. }
  1829. private void MultiEdit_Click(object sender, RoutedEventArgs e)
  1830. {
  1831. using (new WaitCursor())
  1832. {
  1833. var criteria = new Filters<T>();
  1834. var columns = new Columns<T>();
  1835. columns.Add("ID");
  1836. var iprops = DatabaseSchema.Properties(typeof(T)).Where(x => x.Editor is not NullEditor);
  1837. foreach (var iprop in iprops)
  1838. columns.Add(iprop.Name);
  1839. var sort = LookupFactory.DefineSort<T>();
  1840. Reload(
  1841. criteria,
  1842. columns,
  1843. ref sort,
  1844. (table, exception) =>
  1845. {
  1846. if(table is not null)
  1847. {
  1848. Dispatcher.Invoke(() => { DirectEdit(table); });
  1849. }
  1850. else if(exception is not null)
  1851. {
  1852. Logger.Send(LogType.Error, "", $"Error in MultiEdit: {CoreUtils.FormatException(exception)}");
  1853. MessageBox.Show(exception.Message);
  1854. }
  1855. }
  1856. );
  1857. }
  1858. }
  1859. public override bool DirectEdit(CoreTable data)
  1860. {
  1861. var window = new DynamicEditWindow<T>();
  1862. window.OnCreateItem += () => CreateItem();
  1863. window.OnCustomiseColumns += (o, c) =>
  1864. {
  1865. ConfigureColumns(MasterColumns);
  1866. if (OnCustomiseColumns != null)
  1867. return OnCustomiseColumns(this, MasterColumns);
  1868. return MasterColumns;
  1869. };
  1870. window.OnGetEditor += c =>
  1871. {
  1872. var result = GetEditor(this, c)?.CloneEditor();
  1873. if (result == null)
  1874. return null;
  1875. OnCustomiseEditor?.Invoke(window, null, c, result);
  1876. return result;
  1877. };
  1878. window.OnGetSequence += c =>
  1879. {
  1880. decimal result = 0.0M;
  1881. var customprop = DatabaseSchema.Property(typeof(T), c.ColumnName);
  1882. if (customprop != null && customprop is CustomProperty)
  1883. {
  1884. result = customprop.Sequence;
  1885. }
  1886. else
  1887. {
  1888. var bits = c.ColumnName.Split('.');
  1889. for (var i = 0; i < bits.Length; i++)
  1890. {
  1891. var sProp = string.Join(".", bits.Take(bits.Length - i));
  1892. PropertyInfo? prop;
  1893. try
  1894. {
  1895. prop = CoreUtils.GetProperty(typeof(T), sProp);
  1896. }
  1897. catch (Exception e)
  1898. {
  1899. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1900. prop = null;
  1901. }
  1902. if (prop != null)
  1903. {
  1904. result = prop.GetSequence() + result / 1000.0M;
  1905. }
  1906. else
  1907. {
  1908. var cprop = DatabaseSchema.Property(typeof(T), sProp);
  1909. if (cprop != null)
  1910. result = cprop.Sequence;
  1911. else
  1912. result /= 1000.0M;
  1913. }
  1914. }
  1915. }
  1916. return result;
  1917. };
  1918. window.Load(data);
  1919. if (window.ShowDialog() == true)
  1920. {
  1921. SaveItems(window.Updates);
  1922. return true;
  1923. }
  1924. return false;
  1925. }
  1926. protected virtual void DoAdd()
  1927. {
  1928. //CoreRow row = (SelectedRow > -1) && (SelectedRow < Data.Rows.Count) ? Data.Rows[this.SelectedRow] : null;
  1929. if (AddEditClick(null))
  1930. {
  1931. Refresh(false, true);
  1932. OnChanged?.Invoke(this);
  1933. }
  1934. }
  1935. private void Add_Click(object sender, RoutedEventArgs e)
  1936. {
  1937. DoAdd();
  1938. }
  1939. public virtual DynamicEditorPages LoadEditorPages(T item)
  1940. {
  1941. DynamicEditorPages pages = new DynamicEditorPages();
  1942. DynamicGridUtils.LoadOneToManyPages(typeof(T), pages);
  1943. DynamicGridUtils.LoadEnclosedListPages(typeof(T), pages);
  1944. DynamicGridUtils.LoadManyToManyPages(typeof(T), pages);
  1945. DynamicGridUtils.LoadCustomEditorPages(typeof(T), pages);
  1946. foreach (var page in pages)
  1947. page.Ready = false;
  1948. return pages;
  1949. }
  1950. public virtual void LoadEditorButtons(T item, DynamicEditorButtons buttons)
  1951. {
  1952. buttons.Add(
  1953. "",
  1954. Properties.Resources.help.AsBitmapImage(),
  1955. item,
  1956. (f, i) =>
  1957. {
  1958. Process.Start(new ProcessStartInfo("https://prs-software.com.au/wiki/index.php/" + typeof(T).Name.SplitCamelCase().Replace(" ", "_"))
  1959. { UseShellExecute = true });
  1960. }
  1961. );
  1962. }
  1963. protected virtual void CustomiseEditorForm(DynamicEditorForm form)
  1964. {
  1965. }
  1966. public override bool EditItems(T[] items, Func<Type, CoreTable>? PageDataHandler = null, bool PreloadPages = false)
  1967. {
  1968. var cursor = new WaitCursor();
  1969. var pages = items.Length == 1 ? LoadEditorPages(items.First()) : new DynamicEditorPages();
  1970. var buttons = new DynamicEditorButtons();
  1971. if (items.Length == 1)
  1972. LoadEditorButtons(items.First(), buttons);
  1973. var editor = new DynamicEditorForm(items.Any() ? items.First().GetType() : typeof(T), pages, buttons, PageDataHandler, PreloadPages);
  1974. editor.SetValue(Panel.ZIndexProperty, 999);
  1975. editor.OnCustomiseColumns += (o, c) =>
  1976. {
  1977. ConfigureColumns(MasterColumns /*, true */);
  1978. return MasterColumns;
  1979. };
  1980. editor.OnDefineEditor += (o, c) =>
  1981. {
  1982. var result = GetEditor(o, c);
  1983. if (result != null)
  1984. result = result.CloneEditor();
  1985. return result;
  1986. };
  1987. editor.OnFormCustomiseEditor += (o, i, c, e) => OnCustomiseEditor?.Invoke(o, (T[])i, c, e);
  1988. editor.OnDefineFilter += (sender, type) => { return DefineFilter(type, items); };
  1989. //editor.OnDefineFilter += (o, e) => { return DefineFilter(items, e); };
  1990. editor.OnDefineLookups += sender => { DefineLookups(sender, items); };
  1991. editor.OnLookupsDefined += sender => { LookupsDefined(sender, items); };
  1992. editor.OnEditorValueChanged += (s, n, v) => { return EditorValueChanged(editor, items, n, v); };
  1993. editor.ReconfigureEditors += g => { ReconfigureEditors(g, items); };
  1994. editor.OnValidateData += (o, i) => { return ValidateData(items); };
  1995. editor.OnSelectPage += SelectPage;
  1996. editor.OnGetDocument += LoadDocument;
  1997. editor.OnFindDocument += FindDocument;
  1998. editor.OnSaveDocument += SaveDocument;
  1999. editor.OnSaveItem += (o, e) =>
  2000. {
  2001. try
  2002. {
  2003. using var Wait = new WaitCursor();
  2004. OnBeforeSave?.Invoke(editor, items);
  2005. if (items.Length == 1)
  2006. editor.UnloadEditorPages(pages, items.First(), false);
  2007. foreach (var item in items)
  2008. SaveItem(item);
  2009. if (items.Length == 1)
  2010. editor.UnloadEditorPages(pages, items.First(), true);
  2011. OnAfterSave?.Invoke(editor, items);
  2012. }
  2013. catch (Exception err)
  2014. {
  2015. MessageBox.Show(err.Message);
  2016. e.Cancel = true;
  2017. }
  2018. };
  2019. CustomiseEditorForm(editor);
  2020. editor.Items = items;
  2021. AfterLoad(editor, items);
  2022. cursor.Dispose();
  2023. return editor.ShowDialog() == true;
  2024. }
  2025. private void UpdateEditor(DynamicEditorGrid grid, Expression<Func<IDimensioned, object?>> property, bool enabled)
  2026. {
  2027. if (!grid.TryFindEditor(new Column<IDimensioned>(property).Property, out var editor))
  2028. return;
  2029. editor.IsEnabled = enabled;
  2030. if (!enabled)
  2031. editor.SetValue(0D);
  2032. else
  2033. {
  2034. var value = editor.GetValue();
  2035. editor.SetValue(value);
  2036. }
  2037. }
  2038. protected virtual void ReconfigureEditors(DynamicEditorGrid grid, T[] items)
  2039. {
  2040. if (items.First() is IDimensioned dimensioned)
  2041. {
  2042. UpdateEditor(grid, x => x.Dimensions.Quantity, dimensioned.Dimensions.GetUnit().HasQuantity);
  2043. UpdateEditor(grid, x => x.Dimensions.Length, dimensioned.Dimensions.GetUnit().HasLength);
  2044. UpdateEditor(grid, x => x.Dimensions.Width, dimensioned.Dimensions.GetUnit().HasWidth);
  2045. UpdateEditor(grid, x => x.Dimensions.Height, dimensioned.Dimensions.GetUnit().HasHeight);
  2046. UpdateEditor(grid, x => x.Dimensions.Weight, dimensioned.Dimensions.GetUnit().HasWeight);
  2047. }
  2048. }
  2049. private string[]? ValidateData(T[] items)
  2050. {
  2051. var errors = new List<string>();
  2052. DoValidate(items, errors);
  2053. OnValidate?.Invoke(this, items, errors);
  2054. return errors.Any() ? errors.ToArray() : null;
  2055. }
  2056. protected virtual void DoValidate(T[] items, List<string> errors)
  2057. {
  2058. }
  2059. protected virtual void AfterLoad(DynamicEditorForm editor, T[] items)
  2060. {
  2061. }
  2062. protected virtual void SelectPage(object sender, BaseObject[]? items)
  2063. {
  2064. }
  2065. protected virtual Dictionary<string, object?> EditorValueChanged(DynamicEditorForm editor, T[] items, string name, object value)
  2066. {
  2067. var result = DynamicGridUtils.UpdateEditorValue(items, name, value);
  2068. if (OnEditorValueChanged != null)
  2069. {
  2070. var newchanges = OnEditorValueChanged(editor, name, value);
  2071. foreach (var key in newchanges.Keys)
  2072. result[key] = newchanges[key];
  2073. }
  2074. return result;
  2075. }
  2076. private readonly Dictionary<Tuple<Type, Type>, Dictionary<object, object>> _lookupcache = new();
  2077. protected virtual void LookupsDefined(ILookupEditorControl sender, T[] items)
  2078. {
  2079. }
  2080. protected virtual void DefineLookups(ILookupEditorControl sender, T[] items)
  2081. {
  2082. if (sender.EditorDefinition is not ILookupEditor editor)
  2083. return;
  2084. var colname = sender.ColumnName;
  2085. //Logger.Send(LogType.Information, typeof(T).Name, "Into Define Lookups: " + colname);
  2086. Task.Run(() =>
  2087. {
  2088. try
  2089. {
  2090. var values = editor.Values(colname, items);
  2091. Dispatcher.Invoke(
  2092. () =>
  2093. {
  2094. try
  2095. {
  2096. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  2097. sender.LoadLookups(values);
  2098. }
  2099. catch (Exception e2)
  2100. {
  2101. Logger.Send(LogType.Information, typeof(T).Name,
  2102. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  2103. }
  2104. }
  2105. );
  2106. }
  2107. catch (Exception e)
  2108. {
  2109. Logger.Send(LogType.Information, typeof(T).Name, "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  2110. }
  2111. });
  2112. }
  2113. /// <summary>
  2114. /// Retrieves an editor to display for the given column of <paramref name="item"/>.
  2115. /// </summary>
  2116. /// <param name="item">The object being edited.</param>
  2117. /// <param name="column">The column of the editor.</param>
  2118. /// <returns>A new editor, or <see langword="null"/> if no editor defined and no sensible default exists.</returns>
  2119. protected virtual BaseEditor? GetEditor(object item, DynamicGridColumn column)
  2120. {
  2121. return column.Editor ?? CoreUtils.GetProperty(item.GetType(), column.ColumnName).GetEditor();
  2122. }
  2123. protected object DefineFilter(Type type, T[] items)
  2124. {
  2125. return LookupFactory.DefineFilter(items, type);
  2126. }
  2127. protected virtual void SetEditorValue(object item, string name, object value)
  2128. {
  2129. try
  2130. {
  2131. CoreUtils.SetPropertyValue(item, name, value);
  2132. }
  2133. catch (Exception e)
  2134. {
  2135. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2136. }
  2137. }
  2138. protected virtual object? GetEditorValue(object item, string name)
  2139. {
  2140. return CoreUtils.GetPropertyValue(item, name);
  2141. }
  2142. protected virtual Document? LoadDocument(Guid id)
  2143. {
  2144. return null;
  2145. }
  2146. protected virtual Document? FindDocument(string filename)
  2147. {
  2148. return null;
  2149. }
  2150. protected virtual void SaveDocument(Document document)
  2151. {
  2152. }
  2153. private bool AddEditClick(CoreRow[]? rows)
  2154. {
  2155. if (!IsEnabled || bRefreshing)
  2156. return false;
  2157. if (rows == null || !rows.Any())
  2158. {
  2159. var item = CreateItem();
  2160. // Yea, and this won't work, because we're actually usually showing the description of a linked item,
  2161. // not the id of the link, and we need to set the ID to have it work properly :-(
  2162. //foreach (String key in VisualFilters.Keys)
  2163. // CoreUtils.SetPropertyValue(item, key, VisualFilters[key]);
  2164. if (EditItems(new[] { item }))
  2165. {
  2166. //_CurrentRow = Data.Rows.Count;
  2167. var row = Data.NewRow();
  2168. ObjectToRow(item, row);
  2169. Data.Rows.Add(row);
  2170. InvalidateGrid();
  2171. SelectedRows = new[] { row };
  2172. OnChanged?.Invoke(this);
  2173. return true;
  2174. }
  2175. return false;
  2176. }
  2177. var items = Array.Empty<T>();
  2178. using (new WaitCursor())
  2179. {
  2180. Stopwatch sw = new Stopwatch();
  2181. sw.Start();
  2182. items = LoadItems(rows);
  2183. //Logger.Send(LogType.Information, "DG:LoadItems", String.Format("Loaded Items: {0}ms", sw.ElapsedMilliseconds));
  2184. sw.Stop();
  2185. }
  2186. if (items.Any())
  2187. {
  2188. var sel = SelectedRows;
  2189. if (EditItems(items))
  2190. {
  2191. for (var i = 0; i < items.Length; i++)
  2192. ObjectToRow(items[i], rows[i]);
  2193. InvalidateGrid();
  2194. SelectedRows = sel;
  2195. OnChanged?.Invoke(this);
  2196. return true;
  2197. }
  2198. return false;
  2199. }
  2200. return false;
  2201. }
  2202. #endregion
  2203. #region Duplicate
  2204. protected virtual IEnumerable<T> LoadDuplicatorItems(CoreRow[] rows)
  2205. {
  2206. return LoadItems(rows);
  2207. }
  2208. private bool DoDuplicate(Button button, CoreRow[] rows)
  2209. {
  2210. if (!rows.Any())
  2211. {
  2212. MessageBox.Show("Please select at least one record to duplicate!");
  2213. return false;
  2214. }
  2215. /*var ids = ExtractValues(x => x.ID, Selection.Selected).ToArray();
  2216. if (!ids.Any())
  2217. {
  2218. MessageBox.Show("Please select at least one record to duplicate!");
  2219. return false;
  2220. }*/
  2221. var duplicator = (new T() as IDuplicatable)?.GetDuplicator();
  2222. if (duplicator is null)
  2223. {
  2224. MessageBox.Show($"Cannot duplicate {typeof(T)}");
  2225. return false;
  2226. }
  2227. duplicator.Duplicate(LoadDuplicatorItems(rows));// new Filter<T>(x => x.ID).InList(ids));
  2228. return true;
  2229. }
  2230. #endregion
  2231. protected virtual void ShowHelp(string slug)
  2232. {
  2233. Process.Start(new ProcessStartInfo("https://prs-software.com.au/wiki/index.php/" + slug) { UseShellExecute = true });
  2234. }
  2235. protected void ReloadForms<TTargetType, TTargetForm, TSourceForm>(DynamicEditorForm editor, TTargetType item,
  2236. Expression<Func<TSourceForm, object?>> sourcekey, Guid sourceid)
  2237. where TTargetType : Entity, new()
  2238. where TTargetForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  2239. where TSourceForm : Entity, IRemotable, IPersistent, IDigitalForm<TTargetType>, new()
  2240. {
  2241. var type = typeof(IDynamicOneToManyGrid<,>).MakeGenericType(typeof(TTargetType), typeof(TTargetForm));
  2242. var page =
  2243. editor.Pages?.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(type)) as IDynamicOneToManyGrid<TTargetType, TTargetForm>;
  2244. if (page != null && item != null)
  2245. {
  2246. if (!page.Ready)
  2247. page.Load(item, null);
  2248. CoreTable table;
  2249. if (sourceid == Guid.Empty)
  2250. {
  2251. table = new CoreTable();
  2252. table.LoadColumns(typeof(TSourceForm));
  2253. }
  2254. else
  2255. {
  2256. table = new Client<TSourceForm>().Query(
  2257. new Filter<TSourceForm>(sourcekey).IsEqualTo(sourceid).And(x => x.Form.AppliesTo)
  2258. .IsEqualTo(typeof(TTargetType).EntityName().Split('.').Last())
  2259. );
  2260. }
  2261. var newforms = new List<TTargetForm>();
  2262. foreach (var row in table.Rows)
  2263. {
  2264. var sourceform = row.ToObject<TSourceForm>();
  2265. var targetform = new TTargetForm();
  2266. targetform.Form.ID = sourceform.Form.ID;
  2267. targetform.Form.Synchronise(sourceform.Form);
  2268. newforms.Add(targetform);
  2269. }
  2270. page.Items.Clear();
  2271. page.LoadItems(newforms.ToArray());
  2272. }
  2273. }
  2274. #region ClipBuffer
  2275. private Tuple<ClipAction, CoreRow[]>? ClipBuffer;
  2276. protected void ResetClipBuffer()
  2277. {
  2278. ClipBuffer = null;
  2279. }
  2280. protected void SetClipBuffer(ClipAction action, CoreRow[] rows)
  2281. {
  2282. ClipBuffer = new Tuple<ClipAction, CoreRow[]>(action, rows);
  2283. }
  2284. private void CutToClipBuffer()
  2285. {
  2286. SetClipBuffer(ClipAction.Cut, SelectedRows);
  2287. InvalidateGrid();
  2288. }
  2289. private void CopyToClipBuffer()
  2290. {
  2291. SetClipBuffer(ClipAction.Copy, SelectedRows);
  2292. InvalidateGrid();
  2293. }
  2294. private void PasteFromClipBuffer()
  2295. {
  2296. if (ClipBuffer == null)
  2297. return;
  2298. if (!IsSequenced)
  2299. return;
  2300. using (new WaitCursor())
  2301. {
  2302. var updates = ClipBuffer.Item2.Select(x => x.ToObject<T>()).ToList();
  2303. if (BeforePaste(updates, ClipBuffer.Item1))
  2304. {
  2305. var currow = SelectedRows.FirstOrDefault()
  2306. ?? Data.Rows.LastOrDefault();
  2307. var sequence = currow != null ? currow.Get<T, long>(c => ((ISequenceable)c).Sequence) : 0;
  2308. var postrows = Data.Rows.Where(r => !ClipBuffer.Item2.Contains(r) && r.Get<ISequenceable, long>(x => x.Sequence) >= sequence);
  2309. updates.AddRange(LoadItems(postrows.ToArray()));
  2310. foreach (var update in updates)
  2311. {
  2312. sequence++;
  2313. ((ISequenceable)update).Sequence = sequence;
  2314. }
  2315. }
  2316. if (updates.Any())
  2317. {
  2318. SaveItems(updates.ToArray());
  2319. Refresh(false, true);
  2320. }
  2321. }
  2322. }
  2323. protected virtual bool BeforePaste(IEnumerable<T> items, ClipAction action)
  2324. {
  2325. return true;
  2326. }
  2327. private void Cut_Click(object sender, RoutedEventArgs e)
  2328. {
  2329. CutToClipBuffer();
  2330. }
  2331. private void Copy_Click(object sender, RoutedEventArgs e)
  2332. {
  2333. CopyToClipBuffer();
  2334. }
  2335. private void Paste_Click(object sender, RoutedEventArgs e)
  2336. {
  2337. PasteFromClipBuffer();
  2338. }
  2339. #endregion
  2340. protected virtual void ObjectToRow(T obj, CoreRow row)
  2341. {
  2342. Data.LoadRow(row, obj);
  2343. }
  2344. #region Import / Export
  2345. protected virtual Guid GetImportID()
  2346. {
  2347. return Guid.Empty;
  2348. }
  2349. protected virtual bool CustomiseImportItem(T item)
  2350. {
  2351. if (IsSequenced)
  2352. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  2353. return true;
  2354. }
  2355. protected virtual string CustomiseImportFileName(string filename)
  2356. {
  2357. return filename;
  2358. }
  2359. private void Import_Click(object sender, RoutedEventArgs e)
  2360. {
  2361. var list = new DynamicImportList(
  2362. typeof(T),
  2363. GetImportID()
  2364. );
  2365. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  2366. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  2367. list.ShowDialog();
  2368. Refresh(false, true);
  2369. }
  2370. protected virtual void CustomiseExportColumns(List<string> columnnames)
  2371. {
  2372. }
  2373. protected virtual string CustomiseExportFileName(string filename)
  2374. {
  2375. return filename;
  2376. }
  2377. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  2378. {
  2379. }
  2380. protected virtual void ApplyExportFilter(CoreTable table, object data)
  2381. {
  2382. }
  2383. private void Export_Click(object sender, RoutedEventArgs e)
  2384. {
  2385. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  2386. CustomiseExportColumns(columnnames);
  2387. var form = new DynamicExportForm(typeof(T), columnnames);
  2388. if (form.ShowDialog() != true)
  2389. return;
  2390. var filters = new Filters<T>();
  2391. filters.Add(DefineFilter());
  2392. var visiblerows = GetVisibleRows();
  2393. CustomiseExportFilters(filters, visiblerows);
  2394. var columns = new Columns<T>(form.Fields);
  2395. var otherColumns = form.GetChildFields()
  2396. .Select(x => new Tuple<Type, IColumns>(
  2397. x.Key,
  2398. (Activator.CreateInstance(typeof(Columns<>).MakeGenericType(x.Key), new object[] { x.Value }) as IColumns)!))
  2399. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  2400. var sort = LookupFactory.DefineSort<T>();
  2401. Reload(filters, columns, ref sort, (data, err) => Dispatcher.Invoke(() => {
  2402. if(data is not null)
  2403. {
  2404. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), data) };
  2405. list.AddRange(LoadExportTables(filters, otherColumns));
  2406. DoExport(list);
  2407. }
  2408. else if (err is not null)
  2409. {
  2410. Logger.Send(LogType.Error, "", $"Error in export: {CoreUtils.FormatException(err)}");
  2411. MessageBox.Show(err.Message);
  2412. }
  2413. }));
  2414. }
  2415. /// <summary>
  2416. /// Loads the child tables for an export, based on the filter of the parent table.
  2417. /// </summary>
  2418. /// <remarks>
  2419. /// If not overriden, defaults to creating empty tables with no records.
  2420. /// </remarks>
  2421. /// <param name="filter">Filter for the parent table.</param>
  2422. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  2423. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  2424. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  2425. {
  2426. return tableColumns.Select(x => {
  2427. var table = new CoreTable();
  2428. table.LoadColumns(x.Item2);
  2429. return new Tuple<Type?, CoreTable>(x.Item1, table);
  2430. });
  2431. }
  2432. private void DoExport(List<Tuple<Type?, CoreTable>> data)
  2433. {
  2434. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  2435. ExcelExporter.DoExport(data, filename);
  2436. }
  2437. #endregion
  2438. public void ScrollIntoView(CoreRow row)
  2439. {
  2440. DataGrid.ScrollInView(new RowColumnIndex(row.Index + 1, 0));
  2441. }
  2442. #endregion
  2443. #region Custom Buttons
  2444. private Button CreateButton(BitmapImage? image = null, string? text = null, string? tooltip = null)
  2445. {
  2446. var button = new Button();
  2447. button.SetValue(BorderBrushProperty, new SolidColorBrush(Colors.Gray));
  2448. button.SetValue(BorderThicknessProperty, new Thickness(0.75));
  2449. button.Height = 30;
  2450. UpdateButton(button, image, text, tooltip);
  2451. return button;
  2452. }
  2453. protected void UpdateButton(Button button, BitmapImage? image, string? text, string? tooltip = null)
  2454. {
  2455. var stackPnl = new StackPanel();
  2456. stackPnl.Orientation = Orientation.Horizontal;
  2457. //stackPnl.Margin = new Thickness(2);
  2458. if (image != null)
  2459. {
  2460. var img = new Image();
  2461. img.Source = image;
  2462. img.Margin = new Thickness(2);
  2463. img.ToolTip = tooltip;
  2464. stackPnl.Children.Add(img);
  2465. }
  2466. if (!string.IsNullOrEmpty(text))
  2467. {
  2468. var lbl = new Label();
  2469. lbl.Content = text;
  2470. lbl.VerticalAlignment = VerticalAlignment.Stretch;
  2471. lbl.VerticalContentAlignment = VerticalAlignment.Center;
  2472. lbl.Margin = new Thickness(2, 0, 5, 0);
  2473. lbl.ToolTip = ToolTip;
  2474. stackPnl.Children.Add(lbl);
  2475. }
  2476. button.Content = stackPnl;
  2477. button.ToolTip = tooltip;
  2478. }
  2479. private bool bFirstButtonAdded = true;
  2480. private bool AnyButtonsVisible()
  2481. {
  2482. if (Add.Visibility != Visibility.Collapsed)
  2483. return true;
  2484. if (Edit.Visibility != Visibility.Collapsed)
  2485. return true;
  2486. if (MultiEdit.Visibility != Visibility.Collapsed)
  2487. return true;
  2488. if (Export.Visibility != Visibility.Collapsed)
  2489. return true;
  2490. return false;
  2491. }
  2492. public Button AddButton(string caption, BitmapImage? image, string? tooltip, Func<Button, CoreRow[], bool> action)
  2493. {
  2494. var button = CreateButton(image, caption, tooltip);
  2495. button.Margin = new Thickness(bFirstButtonAdded && AnyButtonsVisible() ? /* 10 */ 0 : 0, 2, 2, 0);
  2496. button.Padding = new Thickness(5, 0, 5, 0);
  2497. button.Tag = action;
  2498. button.Click += Button_Click;
  2499. Stack.Children.Add(button);
  2500. bFirstButtonAdded = false;
  2501. return button;
  2502. }
  2503. public Button AddButton(string caption, BitmapImage? image, Func<Button, CoreRow[], bool> action)
  2504. {
  2505. var result = AddButton(caption, image, null, action);
  2506. return result;
  2507. }
  2508. private void Button_Click(object sender, RoutedEventArgs e)
  2509. {
  2510. var button = (Button)sender;
  2511. var action = (Func<Button, CoreRow[], bool>)button.Tag;
  2512. //CoreRow row = (CurrentRow > -1) && (CurrentRow < Data.Rows.Count) ? Data.Rows[this.CurrentRow] : null;
  2513. if (action.Invoke(button, SelectedRows))
  2514. Refresh(false, true);
  2515. }
  2516. #endregion
  2517. #region Header Actions
  2518. private void SelectColumnsClick(object sender, RoutedEventArgs e)
  2519. {
  2520. var editor = new DynamicGridColumnsEditor(typeof(T));
  2521. editor.DirectEdit = Options.Contains(DynamicGridOption.DirectEdit);
  2522. editor.Columns.AddRange(VisibleColumns);
  2523. if (editor.ShowDialog().Equals(true))
  2524. {
  2525. VisibleColumns.Clear();
  2526. VisibleColumns.AddRange(editor.Columns);
  2527. SaveColumns(VisibleColumns);
  2528. //OnSaveColumns?.Invoke(this, editor.Columns);
  2529. Refresh(true, true);
  2530. }
  2531. }
  2532. #endregion
  2533. /* Removed as appears unused; removed as of 19/12/2022
  2534. #region CellRendering
  2535. private void PopulateDynamicActionCell(DynamicActionColumn column, int rowIndex, int columnIndex, GridStyleInfo style)
  2536. {
  2537. style.CellType = "ImageCell";
  2538. var bi = column.Image?.Invoke(rowIndex < 0 ? null : Data.Rows[rowIndex]);
  2539. if (bi != null)
  2540. {
  2541. style.CellValue = bi;
  2542. style.BorderMargins = new CellMarginsInfo(4.0F);
  2543. }
  2544. }
  2545. //bool rowstylehelperinitialised = false;
  2546. //protected virtual void ProcessCellStyle(CoreRow row, int column, GridStyleInfo style)
  2547. //{
  2548. // if (!rowstylehelperinitialised)
  2549. // {
  2550. // Script stylescript = new Client<Script>().Load(new Filter<Script>(x => x.Section).IsEqualTo(typeof(T).EntityName()).And(x => x.ScriptType).IsEqualTo(ScriptType.RowStyle)).FirstOrDefault(); ;
  2551. // if (stylescript != null)
  2552. // {
  2553. // rowstylehelper = new ScriptDocument(stylescript.Code);
  2554. // if (!rowstylehelper.Compile())
  2555. // {
  2556. // MessageBox.Show("Unable to Load Row Style Helper!\r\n\r\n" + rowstylehelper.Result);
  2557. // rowstylehelper = null;
  2558. // }
  2559. // }
  2560. // rowstylehelperinitialised = true;
  2561. // }
  2562. // if (rowstylehelper != null)
  2563. // {
  2564. // try
  2565. // {
  2566. // rowstylehelper.SetValue("Row", row);
  2567. // rowstylehelper.SetValue("Column", Data.Columns[column].ColumnName);
  2568. // rowstylehelper.SetValue("Background", style.Background);
  2569. // rowstylehelper.SetValue("Foreground", style.Foreground);
  2570. // rowstylehelper.SetValue("Style", style.Font.FontStyle);
  2571. // rowstylehelper.SetValue("Weight", style.Font.FontWeight);
  2572. // if (rowstylehelper.Execute())
  2573. // {
  2574. // style.Background = (System.Windows.Media.Brush)rowstylehelper.GetValue("Background");
  2575. // style.Foreground = (System.Windows.Media.Brush)rowstylehelper.GetValue("Foreground");
  2576. // style.Font.FontStyle = (FontStyle)rowstylehelper.GetValue("Style");
  2577. // style.Font.FontWeight = (FontWeight)rowstylehelper.GetValue("Weight");
  2578. // }
  2579. // }
  2580. // catch (Exception e)
  2581. // {
  2582. // //MessageBox.Show("Unable to Invoke Row Style Helper!\r\n\r\n" + e.Message);
  2583. // }
  2584. // }
  2585. //}
  2586. private readonly Dictionary<string, BaseEditor> editorcache = new();
  2587. private void PopulateDataCell(int rowIndex, int columnIndex, GridStyleInfo style)
  2588. {
  2589. if (columnIndex > -1 && columnIndex < ColumnList.Count)
  2590. {
  2591. var o = ColumnList[columnIndex];
  2592. if (o is DynamicActionColumn)
  2593. {
  2594. PopulateDynamicActionCell((DynamicActionColumn)o, rowIndex, columnIndex, style);
  2595. }
  2596. else
  2597. {
  2598. var dgc = (DynamicGridColumn)o;
  2599. var dc = Data.Columns.FirstOrDefault(x => x.ColumnName.Equals(dgc.ColumnName));
  2600. var fmt = string.IsNullOrWhiteSpace(dgc.Format) ? "{0}" : "{0:" + dgc.Format.Replace("\\:", ":").Replace(":", "\\:") + "}";
  2601. object? val = null;
  2602. if (rowIndex < Data.Rows.Count)
  2603. val = Data.Rows[rowIndex][dgc.ColumnName];
  2604. if (val != null && dgc.Lookups.ContainsKey(val))
  2605. val = dgc.Lookups[val];
  2606. if (dc != null)
  2607. {
  2608. if(!editorcache.TryGetValue(dc.ColumnName, out var editor))
  2609. {
  2610. var prop = DatabaseSchema.Property(typeof(T), dc.ColumnName);
  2611. if (prop != null)
  2612. editor = prop.Editor;
  2613. else
  2614. editor = EditorUtils.GetEditor(dc.DataType) ?? new NullEditor();
  2615. editorcache[dc.ColumnName] = editor;
  2616. }
  2617. if (editor is CheckBoxEditor)
  2618. {
  2619. style.CellType = "CheckBox";
  2620. style.CellValue = val;
  2621. style.HorizontalAlignment = dc == null ? HorizontalAlignment.Left : dgc.HorizontalAlignment(dc.DataType);
  2622. style.VerticalAlignment = dgc.VerticalAlignment();
  2623. style.TextMargins = new CellMarginsInfo(2.0F);
  2624. }
  2625. else if (editor is ColorEditor)
  2626. {
  2627. style.CellType = "ImageCell";
  2628. var str = val?.ToString();
  2629. if (!string.IsNullOrWhiteSpace(str))
  2630. {
  2631. var color = ColorTranslator.FromHtml(str); // System.Drawing.Color.FromName(val.ToString());
  2632. var bitmap = ImageUtils.BitmapFromColor(color, (int)style.GridModel.ColumnWidths[columnIndex],
  2633. (int)style.GridModel.RowHeights[rowIndex], Color.Black);
  2634. //bitmap.Save(val.ToString().Replace("#","") + ".png");
  2635. style.CellValue = bitmap.AsBitmapImage(false);
  2636. style.BorderMargins = new CellMarginsInfo(4.0F);
  2637. }
  2638. }
  2639. else
  2640. {
  2641. string value;
  2642. try
  2643. {
  2644. if(val is null)
  2645. {
  2646. value = "";
  2647. }
  2648. else if (val.GetType().IsEnum)
  2649. {
  2650. value = val.ToString()!;
  2651. }
  2652. else if (val.GetType().IsDefault(val))
  2653. {
  2654. value = "";
  2655. }
  2656. else
  2657. {
  2658. value = string.Format(new TimeSpanFormatter(), fmt, val);
  2659. }
  2660. }
  2661. catch (Exception e)
  2662. {
  2663. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2664. value = val?.ToString() ?? "";
  2665. }
  2666. if (editor is PasswordEditor)
  2667. style.CellValue = "".PadLeft(value.Length, '●');
  2668. else
  2669. style.CellValue = value;
  2670. style.HorizontalAlignment = dc == null ? HorizontalAlignment.Left : dgc.HorizontalAlignment(dc.DataType);
  2671. style.VerticalAlignment = dgc.VerticalAlignment();
  2672. style.CellType = "Static";
  2673. style.TextMargins = new CellMarginsInfo(2.0F);
  2674. }
  2675. }
  2676. }
  2677. }
  2678. }
  2679. private void PopulateHeaderCell(int columnIndex, GridStyleInfo style)
  2680. {
  2681. if (columnIndex > -1 && columnIndex < ColumnList.Count)
  2682. {
  2683. var o = ColumnList[columnIndex];
  2684. if (o is DynamicActionColumn)
  2685. {
  2686. PopulateDynamicActionCell((DynamicActionColumn)o, -1, columnIndex, style);
  2687. }
  2688. else
  2689. {
  2690. var dgc = (DynamicGridColumn)o;
  2691. if (Data != null)
  2692. {
  2693. var dc = Data.Columns.FirstOrDefault(x => x.ColumnName.Equals(dgc.ColumnName));
  2694. style.HorizontalAlignment = dc != null ? dgc.HorizontalAlignment(dc.DataType) : HorizontalAlignment.Left;
  2695. }
  2696. style.CellValue = string.IsNullOrWhiteSpace(dgc.Caption) ? dgc.ColumnName : dgc.Caption;
  2697. style.VerticalAlignment = dgc.VerticalAlignment();
  2698. style.CellType = "Static";
  2699. style.TextMargins = new CellMarginsInfo(2.0F);
  2700. }
  2701. }
  2702. }
  2703. #endregion
  2704. */
  2705. /* Removed as appears unused; removed as of 19/12/2022
  2706. #region Drag and Drop
  2707. private Point startpoint;
  2708. private void CheckPreviewMouseDown(object sender, MouseButtonEventArgs e)
  2709. {
  2710. if (!Options.Contains(DynamicGridOption.DragSource))
  2711. return;
  2712. if (e.LeftButton == MouseButtonState.Pressed)
  2713. {
  2714. Logger.Send(LogType.Information, GetType().EntityName(), "Initiating Start Point");
  2715. startpoint = e.GetPosition(DataGrid);
  2716. }
  2717. }
  2718. //private void CheckPreviewMouseMove(object sender, MouseEventArgs e)
  2719. //{
  2720. // Logger.Send(LogType.Information, this.GetType().EntityName(), String.Format("Checking Mouse Move: StartPoint = {0},{1}", startpoint.X, startpoint.Y));
  2721. // if (!_Options.Contains(DynamicGridOptions.DragSource))
  2722. // return;
  2723. // Vector diff = startpoint - e.GetPosition(null);
  2724. // 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));
  2725. // if ( (startpoint.X != 0) && (startpoint.Y != 0))
  2726. // {
  2727. // if ((Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance) || (Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
  2728. // {
  2729. // Logger.Send(LogType.Information, this.GetType().EntityName(), "Starting Drag Drop Operation");
  2730. // DataObject dragData = new DataObject(typeof(T).EntityName(), SelectedRows);
  2731. // DragDrop.DoDragDrop(DataGrid, dragData, DragDropEffects.Copy);
  2732. // }
  2733. // }
  2734. //}
  2735. private void CheckPreviewMouseUp(object sender, MouseButtonEventArgs e)
  2736. {
  2737. if (!Options.Contains(DynamicGridOption.DragSource))
  2738. return;
  2739. Logger.Send(LogType.Information, GetType().EntityName(), "Clearing Start Point");
  2740. startpoint = new Point();
  2741. }
  2742. #endregion
  2743. */
  2744. }
  2745. }