DynamicGrid.cs 131 KB

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