DynamicGrid.cs 126 KB

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