DynamicGrid.cs 135 KB

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