DynamicGrid.cs 126 KB

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