DynamicGrid.cs 135 KB

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