DynamicGrid.cs 135 KB

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