DynamicGrid.cs 141 KB

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