DataGrid.cs 225 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891
  1. // (c) Copyright Microsoft Corporation.
  2. // This source is subject to the Microsoft Public License (Ms-PL).
  3. // Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
  4. // All other rights reserved.
  5. using Avalonia.Collections;
  6. using Avalonia.Controls.Primitives;
  7. using Avalonia.Controls.Templates;
  8. using Avalonia.Data;
  9. using Avalonia.Input;
  10. using Avalonia.Interactivity;
  11. using Avalonia.Media;
  12. using Avalonia.VisualTree;
  13. using Avalonia.Utilities;
  14. using System;
  15. using System.Collections;
  16. using System.Collections.Generic;
  17. using System.Collections.ObjectModel;
  18. using System.Collections.Specialized;
  19. using System.ComponentModel;
  20. using System.Diagnostics;
  21. using System.Text;
  22. using System.Linq;
  23. using Avalonia.Input.Platform;
  24. using System.ComponentModel.DataAnnotations;
  25. using Avalonia.Controls.Utils;
  26. using Avalonia.Layout;
  27. namespace Avalonia.Controls
  28. {
  29. /// <summary>
  30. /// Displays data in a customizable grid.
  31. /// </summary>
  32. public partial class DataGrid : TemplatedControl
  33. {
  34. private const string DATAGRID_elementRowsPresenterName = "PART_RowsPresenter";
  35. private const string DATAGRID_elementColumnHeadersPresenterName = "PART_ColumnHeadersPresenter";
  36. private const string DATAGRID_elementFrozenColumnScrollBarSpacerName = "PART_FrozenColumnScrollBarSpacer";
  37. private const string DATAGRID_elementHorizontalScrollbarName = "PART_HorizontalScrollbar";
  38. private const string DATAGRID_elementRowHeadersPresenterName = "PART_RowHeadersPresenter";
  39. private const string DATAGRID_elementTopLeftCornerHeaderName = "PART_TopLeftCornerHeader";
  40. private const string DATAGRID_elementTopRightCornerHeaderName = "PART_TopRightCornerHeader";
  41. private const string DATAGRID_elementValidationSummary = "PART_ValidationSummary";
  42. private const string DATAGRID_elementVerticalScrollbarName = "PART_VerticalScrollbar";
  43. private const bool DATAGRID_defaultAutoGenerateColumns = true;
  44. internal const bool DATAGRID_defaultCanUserReorderColumns = true;
  45. internal const bool DATAGRID_defaultCanUserResizeColumns = true;
  46. internal const bool DATAGRID_defaultCanUserSortColumns = true;
  47. private const DataGridRowDetailsVisibilityMode DATAGRID_defaultRowDetailsVisibility = DataGridRowDetailsVisibilityMode.VisibleWhenSelected;
  48. private const DataGridSelectionMode DATAGRID_defaultSelectionMode = DataGridSelectionMode.Extended;
  49. /// <summary>
  50. /// The default order to use for columns when there is no <see cref="DisplayAttribute.Order"/>
  51. /// value available for the property.
  52. /// </summary>
  53. /// <remarks>
  54. /// The value of 10,000 comes from the DataAnnotations spec, allowing
  55. /// some properties to be ordered at the beginning and some at the end.
  56. /// </remarks>
  57. private const int DATAGRID_defaultColumnDisplayOrder = 10000;
  58. private const double DATAGRID_horizontalGridLinesThickness = 1;
  59. private const double DATAGRID_minimumRowHeaderWidth = 4;
  60. private const double DATAGRID_minimumColumnHeaderHeight = 4;
  61. internal const double DATAGRID_maximumStarColumnWidth = 10000;
  62. internal const double DATAGRID_minimumStarColumnWidth = 0.001;
  63. private const double DATAGRID_mouseWheelDelta = 48.0;
  64. private const double DATAGRID_maxHeadersThickness = 32768;
  65. private const double DATAGRID_defaultRowHeight = 22;
  66. internal const double DATAGRID_defaultRowGroupSublevelIndent = 20;
  67. private const double DATAGRID_defaultMinColumnWidth = 20;
  68. private const double DATAGRID_defaultMaxColumnWidth = double.PositiveInfinity;
  69. private List<Exception> _validationErrors;
  70. private List<Exception> _bindingValidationErrors;
  71. private IDisposable _validationSubscription;
  72. private INotifyCollectionChanged _topLevelGroup;
  73. private ContentControl _clipboardContentControl;
  74. private DataGridColumnHeadersPresenter _columnHeadersPresenter;
  75. private DataGridRowsPresenter _rowsPresenter;
  76. private ScrollBar _vScrollBar;
  77. private ScrollBar _hScrollBar;
  78. private ContentControl _topLeftCornerHeader;
  79. private ContentControl _topRightCornerHeader;
  80. private Control _frozenColumnScrollBarSpacer;
  81. // the sum of the widths in pixels of the scrolling columns preceding
  82. // the first displayed scrolling column
  83. private double _horizontalOffset;
  84. // the number of pixels of the firstDisplayedScrollingCol which are not displayed
  85. private double _negHorizontalOffset;
  86. private byte _autoGeneratingColumnOperationCount;
  87. private bool _areHandlersSuspended;
  88. private bool _autoSizingColumns;
  89. private IndexToValueTable<bool> _collapsedSlotsTable;
  90. private DataGridCellCoordinates _currentCellCoordinates;
  91. private Control _clickedElement;
  92. // used to store the current column during a Reset
  93. private int _desiredCurrentColumnIndex;
  94. private int _editingColumnIndex;
  95. // this is a workaround only for the scenarios where we need it, it is not all encompassing nor always updated
  96. private RoutedEventArgs _editingEventArgs;
  97. private bool _executingLostFocusActions;
  98. private bool _flushCurrentCellChanged;
  99. private bool _focusEditingControl;
  100. private IVisual _focusedObject;
  101. private byte _horizontalScrollChangesIgnored;
  102. private DataGridRow _focusedRow;
  103. private bool _ignoreNextScrollBarsLayout;
  104. // Nth row of rows 0..N that make up the RowHeightEstimate
  105. private int _lastEstimatedRow;
  106. private List<DataGridRow> _loadedRows;
  107. // prevents reentry into the VerticalScroll event handler
  108. private Queue<Action> _lostFocusActions;
  109. private int _noSelectionChangeCount;
  110. private int _noCurrentCellChangeCount;
  111. private bool _makeFirstDisplayedCellCurrentCellPending;
  112. private bool _measured;
  113. private int? _mouseOverRowIndex; // -1 is used for the 'new row'
  114. private DataGridColumn _previousCurrentColumn;
  115. private object _previousCurrentItem;
  116. private double[] _rowGroupHeightsByLevel;
  117. private double _rowHeaderDesiredWidth;
  118. private Size? _rowsPresenterAvailableSize;
  119. private bool _scrollingByHeight;
  120. private IndexToValueTable<bool> _showDetailsTable;
  121. private bool _successfullyUpdatedSelection;
  122. private DataGridSelectedItemsCollection _selectedItems;
  123. private bool _temporarilyResetCurrentCell;
  124. private object _uneditedValue; // Represents the original current cell value at the time it enters editing mode.
  125. private ICellEditBinding _currentCellEditBinding;
  126. // An approximation of the sum of the heights in pixels of the scrolling rows preceding
  127. // the first displayed scrolling row. Since the scrolled off rows are discarded, the grid
  128. // does not know their actual height. The heights used for the approximation are the ones
  129. // set as the rows were scrolled off.
  130. private double _verticalOffset;
  131. private byte _verticalScrollChangesIgnored;
  132. private IEnumerable _items;
  133. /// <summary>
  134. /// Identifies the CanUserReorderColumns dependency property.
  135. /// </summary>
  136. public static readonly StyledProperty<bool> CanUserReorderColumnsProperty =
  137. AvaloniaProperty.Register<DataGrid, bool>(nameof(CanUserReorderColumns));
  138. /// <summary>
  139. /// Gets or sets a value that indicates whether the user can change
  140. /// the column display order by dragging column headers with the mouse.
  141. /// </summary>
  142. public bool CanUserReorderColumns
  143. {
  144. get { return GetValue(CanUserReorderColumnsProperty); }
  145. set { SetValue(CanUserReorderColumnsProperty, value); }
  146. }
  147. /// <summary>
  148. /// Identifies the CanUserResizeColumns dependency property.
  149. /// </summary>
  150. public static readonly StyledProperty<bool> CanUserResizeColumnsProperty =
  151. AvaloniaProperty.Register<DataGrid, bool>(nameof(CanUserResizeColumns));
  152. /// <summary>
  153. /// Gets or sets a value that indicates whether the user can adjust column widths using the mouse.
  154. /// </summary>
  155. public bool CanUserResizeColumns
  156. {
  157. get { return GetValue(CanUserResizeColumnsProperty); }
  158. set { SetValue(CanUserResizeColumnsProperty, value); }
  159. }
  160. /// <summary>
  161. /// Identifies the CanUserSortColumns dependency property.
  162. /// </summary>
  163. public static readonly StyledProperty<bool> CanUserSortColumnsProperty =
  164. AvaloniaProperty.Register<DataGrid, bool>(nameof(CanUserSortColumns), true);
  165. /// <summary>
  166. /// Gets or sets a value that indicates whether the user can sort columns by clicking the column header.
  167. /// </summary>
  168. public bool CanUserSortColumns
  169. {
  170. get { return GetValue(CanUserSortColumnsProperty); }
  171. set { SetValue(CanUserSortColumnsProperty, value); }
  172. }
  173. /// <summary>
  174. /// Identifies the ColumnHeaderHeight dependency property.
  175. /// </summary>
  176. public static readonly StyledProperty<double> ColumnHeaderHeightProperty =
  177. AvaloniaProperty.Register<DataGrid, double>(
  178. nameof(ColumnHeaderHeight),
  179. defaultValue: double.NaN,
  180. validate: IsValidColumnHeaderHeight);
  181. private static bool IsValidColumnHeaderHeight(double value)
  182. {
  183. return double.IsNaN(value) ||
  184. (value >= DATAGRID_minimumColumnHeaderHeight && value <= DATAGRID_maxHeadersThickness);
  185. }
  186. /// <summary>
  187. /// Gets or sets the height of the column headers row.
  188. /// </summary>
  189. public double ColumnHeaderHeight
  190. {
  191. get { return GetValue(ColumnHeaderHeightProperty); }
  192. set { SetValue(ColumnHeaderHeightProperty, value); }
  193. }
  194. /// <summary>
  195. /// Identifies the ColumnWidth dependency property.
  196. /// </summary>
  197. public static readonly StyledProperty<DataGridLength> ColumnWidthProperty =
  198. AvaloniaProperty.Register<DataGrid, DataGridLength>(nameof(ColumnWidth), defaultValue: DataGridLength.Auto);
  199. /// <summary>
  200. /// Gets or sets the standard width or automatic sizing mode of columns in the control.
  201. /// </summary>
  202. public DataGridLength ColumnWidth
  203. {
  204. get { return GetValue(ColumnWidthProperty); }
  205. set { SetValue(ColumnWidthProperty, value); }
  206. }
  207. public static readonly StyledProperty<IBrush> AlternatingRowBackgroundProperty =
  208. AvaloniaProperty.Register<DataGrid, IBrush>(nameof(AlternatingRowBackground));
  209. /// <summary>
  210. /// Gets or sets the <see cref="T:System.Windows.Media.Brush" /> that is used to paint the background of odd-numbered rows.
  211. /// </summary>
  212. /// <returns>
  213. /// The brush that is used to paint the background of odd-numbered rows. The default is a
  214. /// <see cref="T:System.Windows.Media.SolidColorBrush" /> with a
  215. /// <see cref="P:System.Windows.Media.SolidColorBrush.Color" /> value of white (ARGB value #00FFFFFF).
  216. /// </returns>
  217. public IBrush AlternatingRowBackground
  218. {
  219. get { return GetValue(AlternatingRowBackgroundProperty); }
  220. set { SetValue(AlternatingRowBackgroundProperty, value); }
  221. }
  222. public static readonly StyledProperty<int> FrozenColumnCountProperty =
  223. AvaloniaProperty.Register<DataGrid, int>(
  224. nameof(FrozenColumnCount),
  225. validate: ValidateFrozenColumnCount);
  226. /// <summary>
  227. /// Gets or sets the number of columns that the user cannot scroll horizontally.
  228. /// </summary>
  229. public int FrozenColumnCount
  230. {
  231. get { return GetValue(FrozenColumnCountProperty); }
  232. set { SetValue(FrozenColumnCountProperty, value); }
  233. }
  234. private static bool ValidateFrozenColumnCount(int value) => value >= 0;
  235. public static readonly StyledProperty<DataGridGridLinesVisibility> GridLinesVisibilityProperty =
  236. AvaloniaProperty.Register<DataGrid, DataGridGridLinesVisibility>(nameof(GridLinesVisibility));
  237. /// <summary>
  238. /// Gets or sets a value that indicates which grid lines separating inner cells are shown.
  239. /// </summary>
  240. public DataGridGridLinesVisibility GridLinesVisibility
  241. {
  242. get { return GetValue(GridLinesVisibilityProperty); }
  243. set { SetValue(GridLinesVisibilityProperty, value); }
  244. }
  245. public static readonly StyledProperty<DataGridHeadersVisibility> HeadersVisibilityProperty =
  246. AvaloniaProperty.Register<DataGrid, DataGridHeadersVisibility>(nameof(HeadersVisibility));
  247. /// <summary>
  248. /// Gets or sets a value that indicates the visibility of row and column headers.
  249. /// </summary>
  250. public DataGridHeadersVisibility HeadersVisibility
  251. {
  252. get { return GetValue(HeadersVisibilityProperty); }
  253. set { SetValue(HeadersVisibilityProperty, value); }
  254. }
  255. public static readonly StyledProperty<IBrush> HorizontalGridLinesBrushProperty =
  256. AvaloniaProperty.Register<DataGrid, IBrush>(nameof(HorizontalGridLinesBrush));
  257. /// <summary>
  258. /// Gets or sets the <see cref="T:System.Windows.Media.Brush" /> that is used to paint grid lines separating rows.
  259. /// </summary>
  260. public IBrush HorizontalGridLinesBrush
  261. {
  262. get { return GetValue(HorizontalGridLinesBrushProperty); }
  263. set { SetValue(HorizontalGridLinesBrushProperty, value); }
  264. }
  265. public static readonly StyledProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty =
  266. AvaloniaProperty.Register<DataGrid, ScrollBarVisibility>(nameof(HorizontalScrollBarVisibility));
  267. /// <summary>
  268. /// Gets or sets a value that indicates how the horizontal scroll bar is displayed.
  269. /// </summary>
  270. public ScrollBarVisibility HorizontalScrollBarVisibility
  271. {
  272. get { return GetValue(HorizontalScrollBarVisibilityProperty); }
  273. set { SetValue(HorizontalScrollBarVisibilityProperty, value); }
  274. }
  275. public static readonly StyledProperty<bool> IsReadOnlyProperty =
  276. AvaloniaProperty.Register<DataGrid, bool>(nameof(IsReadOnly));
  277. /// <summary>
  278. /// Gets or sets a value that indicates whether the user can edit the values in the control.
  279. /// </summary>
  280. public bool IsReadOnly
  281. {
  282. get { return GetValue(IsReadOnlyProperty); }
  283. set { SetValue(IsReadOnlyProperty, value); }
  284. }
  285. public static readonly StyledProperty<bool> AreRowGroupHeadersFrozenProperty =
  286. AvaloniaProperty.Register<DataGrid, bool>(
  287. nameof(AreRowGroupHeadersFrozen),
  288. defaultValue: true);
  289. /// <summary>
  290. /// Gets or sets a value that indicates whether the row group header sections
  291. /// remain fixed at the width of the display area or can scroll horizontally.
  292. /// </summary>
  293. public bool AreRowGroupHeadersFrozen
  294. {
  295. get { return GetValue(AreRowGroupHeadersFrozenProperty); }
  296. set { SetValue(AreRowGroupHeadersFrozenProperty, value); }
  297. }
  298. private void OnAreRowGroupHeadersFrozenChanged(AvaloniaPropertyChangedEventArgs e)
  299. {
  300. var value = (bool)e.NewValue;
  301. ProcessFrozenColumnCount();
  302. // Update elements in the RowGroupHeader that were previously frozen
  303. if (value)
  304. {
  305. if (_rowsPresenter != null)
  306. {
  307. foreach (Control element in _rowsPresenter.Children)
  308. {
  309. if (element is DataGridRowGroupHeader groupHeader)
  310. {
  311. groupHeader.ClearFrozenStates();
  312. }
  313. }
  314. }
  315. }
  316. }
  317. private bool _isValid = true;
  318. public static readonly DirectProperty<DataGrid, bool> IsValidProperty =
  319. AvaloniaProperty.RegisterDirect<DataGrid, bool>(
  320. nameof(IsValid),
  321. o => o.IsValid);
  322. public bool IsValid
  323. {
  324. get { return _isValid; }
  325. internal set
  326. {
  327. SetAndRaise(IsValidProperty, ref _isValid, value);
  328. PseudoClasses.Set(":invalid", !value);
  329. }
  330. }
  331. public static readonly StyledProperty<double> MaxColumnWidthProperty =
  332. AvaloniaProperty.Register<DataGrid, double>(
  333. nameof(MaxColumnWidth),
  334. defaultValue: DATAGRID_defaultMaxColumnWidth,
  335. validate: IsValidColumnWidth);
  336. private static bool IsValidColumnWidth(double value)
  337. {
  338. return !double.IsNaN(value) && value > 0;
  339. }
  340. /// <summary>
  341. /// Gets or sets the maximum width of columns in the <see cref="T:Avalonia.Controls.DataGrid" /> .
  342. /// </summary>
  343. public double MaxColumnWidth
  344. {
  345. get { return GetValue(MaxColumnWidthProperty); }
  346. set { SetValue(MaxColumnWidthProperty, value); }
  347. }
  348. public static readonly StyledProperty<double> MinColumnWidthProperty =
  349. AvaloniaProperty.Register<DataGrid, double>(
  350. nameof(MinColumnWidth),
  351. defaultValue: DATAGRID_defaultMinColumnWidth,
  352. validate: IsValidMinColumnWidth);
  353. private static bool IsValidMinColumnWidth(double value)
  354. {
  355. return !double.IsNaN(value) && !double.IsPositiveInfinity(value) && value >= 0;
  356. }
  357. /// <summary>
  358. /// Gets or sets the minimum width of columns in the <see cref="T:Avalonia.Controls.DataGrid" />.
  359. /// </summary>
  360. public double MinColumnWidth
  361. {
  362. get { return GetValue(MinColumnWidthProperty); }
  363. set { SetValue(MinColumnWidthProperty, value); }
  364. }
  365. public static readonly StyledProperty<IBrush> RowBackgroundProperty =
  366. AvaloniaProperty.Register<DataGrid, IBrush>(nameof(RowBackground));
  367. /// <summary>
  368. /// Gets or sets the <see cref="T:System.Windows.Media.Brush" /> that is used to paint row backgrounds.
  369. /// </summary>
  370. public IBrush RowBackground
  371. {
  372. get { return GetValue(RowBackgroundProperty); }
  373. set { SetValue(RowBackgroundProperty, value); }
  374. }
  375. public static readonly StyledProperty<double> RowHeightProperty =
  376. AvaloniaProperty.Register<DataGrid, double>(
  377. nameof(RowHeight),
  378. defaultValue: double.NaN,
  379. validate: IsValidRowHeight);
  380. private static bool IsValidRowHeight(double value)
  381. {
  382. return double.IsNaN(value) ||
  383. (value >= DataGridRow.DATAGRIDROW_minimumHeight &&
  384. value <= DataGridRow.DATAGRIDROW_maximumHeight);
  385. }
  386. /// <summary>
  387. /// Gets or sets the standard height of rows in the control.
  388. /// </summary>
  389. public double RowHeight
  390. {
  391. get { return GetValue(RowHeightProperty); }
  392. set { SetValue(RowHeightProperty, value); }
  393. }
  394. public static readonly StyledProperty<double> RowHeaderWidthProperty =
  395. AvaloniaProperty.Register<DataGrid, double>(
  396. nameof(RowHeaderWidth),
  397. defaultValue: double.NaN,
  398. validate: IsValidRowHeaderWidth);
  399. private static bool IsValidRowHeaderWidth(double value)
  400. {
  401. return double.IsNaN(value) ||
  402. (value >= DATAGRID_minimumRowHeaderWidth &&
  403. value <= DATAGRID_maxHeadersThickness);
  404. }
  405. /// <summary>
  406. /// Gets or sets the width of the row header column.
  407. /// </summary>
  408. public double RowHeaderWidth
  409. {
  410. get { return GetValue(RowHeaderWidthProperty); }
  411. set { SetValue(RowHeaderWidthProperty, value); }
  412. }
  413. public static readonly StyledProperty<DataGridSelectionMode> SelectionModeProperty =
  414. AvaloniaProperty.Register<DataGrid, DataGridSelectionMode>(nameof(SelectionMode));
  415. /// <summary>
  416. /// Gets or sets the selection behavior of the data grid.
  417. /// </summary>
  418. public DataGridSelectionMode SelectionMode
  419. {
  420. get { return GetValue(SelectionModeProperty); }
  421. set { SetValue(SelectionModeProperty, value); }
  422. }
  423. public static readonly StyledProperty<IBrush> VerticalGridLinesBrushProperty =
  424. AvaloniaProperty.Register<DataGrid, IBrush>(nameof(VerticalGridLinesBrush));
  425. /// <summary>
  426. /// Gets or sets the <see cref="T:System.Windows.Media.Brush" /> that is used to paint grid lines separating columns.
  427. /// </summary>
  428. public IBrush VerticalGridLinesBrush
  429. {
  430. get { return GetValue(VerticalGridLinesBrushProperty); }
  431. set { SetValue(VerticalGridLinesBrushProperty, value); }
  432. }
  433. public static readonly StyledProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty =
  434. AvaloniaProperty.Register<DataGrid, ScrollBarVisibility>(nameof(VerticalScrollBarVisibility));
  435. /// <summary>
  436. /// Gets or sets a value that indicates how the vertical scroll bar is displayed.
  437. /// </summary>
  438. public ScrollBarVisibility VerticalScrollBarVisibility
  439. {
  440. get { return GetValue(VerticalScrollBarVisibilityProperty); }
  441. set { SetValue(VerticalScrollBarVisibilityProperty, value); }
  442. }
  443. public static readonly StyledProperty<ITemplate<IControl>> DropLocationIndicatorTemplateProperty =
  444. AvaloniaProperty.Register<DataGrid, ITemplate<IControl>>(nameof(DropLocationIndicatorTemplate));
  445. /// <summary>
  446. /// Gets or sets the template that is used when rendering the column headers.
  447. /// </summary>
  448. public ITemplate<IControl> DropLocationIndicatorTemplate
  449. {
  450. get { return GetValue(DropLocationIndicatorTemplateProperty); }
  451. set { SetValue(DropLocationIndicatorTemplateProperty, value); }
  452. }
  453. private int _selectedIndex = -1;
  454. private object _selectedItem;
  455. public static readonly DirectProperty<DataGrid, int> SelectedIndexProperty =
  456. AvaloniaProperty.RegisterDirect<DataGrid, int>(
  457. nameof(SelectedIndex),
  458. o => o.SelectedIndex,
  459. (o, v) => o.SelectedIndex = v);
  460. /// <summary>
  461. /// Gets or sets the index of the current selection.
  462. /// </summary>
  463. /// <returns>
  464. /// The index of the current selection, or -1 if the selection is empty.
  465. /// </returns>
  466. public int SelectedIndex
  467. {
  468. get { return _selectedIndex; }
  469. set { SetAndRaise(SelectedIndexProperty, ref _selectedIndex, value); }
  470. }
  471. public static readonly DirectProperty<DataGrid, object> SelectedItemProperty =
  472. AvaloniaProperty.RegisterDirect<DataGrid, object>(
  473. nameof(SelectedItem),
  474. o => o.SelectedItem,
  475. (o, v) => o.SelectedItem = v);
  476. /// <summary>
  477. /// Gets or sets the data item corresponding to the selected row.
  478. /// </summary>
  479. public object SelectedItem
  480. {
  481. get { return _selectedItem; }
  482. set { SetAndRaise(SelectedItemProperty, ref _selectedItem, value); }
  483. }
  484. public static readonly StyledProperty<DataGridClipboardCopyMode> ClipboardCopyModeProperty =
  485. AvaloniaProperty.Register<DataGrid, DataGridClipboardCopyMode>(
  486. nameof(ClipboardCopyMode),
  487. defaultValue: DataGridClipboardCopyMode.ExcludeHeader);
  488. /// <summary>
  489. /// The property which determines how DataGrid content is copied to the Clipboard.
  490. /// </summary>
  491. public DataGridClipboardCopyMode ClipboardCopyMode
  492. {
  493. get { return GetValue(ClipboardCopyModeProperty); }
  494. set { SetValue(ClipboardCopyModeProperty, value); }
  495. }
  496. public static readonly StyledProperty<bool> AutoGenerateColumnsProperty =
  497. AvaloniaProperty.Register<DataGrid, bool>(nameof(AutoGenerateColumns));
  498. /// <summary>
  499. /// Gets or sets a value that indicates whether columns are created
  500. /// automatically when the <see cref="P:Avalonia.Controls.DataGrid.ItemsSource" /> property is set.
  501. /// </summary>
  502. public bool AutoGenerateColumns
  503. {
  504. get { return GetValue(AutoGenerateColumnsProperty); }
  505. set { SetValue(AutoGenerateColumnsProperty, value); }
  506. }
  507. private void OnAutoGenerateColumnsChanged(AvaloniaPropertyChangedEventArgs e)
  508. {
  509. var value = (bool)e.NewValue;
  510. if (value)
  511. {
  512. InitializeElements(recycleRows: false);
  513. }
  514. else
  515. {
  516. RemoveAutoGeneratedColumns();
  517. }
  518. }
  519. /// <summary>
  520. /// Identifies the ItemsSource dependency property.
  521. /// </summary>
  522. public static readonly DirectProperty<DataGrid, IEnumerable> ItemsProperty =
  523. AvaloniaProperty.RegisterDirect<DataGrid, IEnumerable>(
  524. nameof(Items),
  525. o => o.Items,
  526. (o, v) => o.Items = v);
  527. /// <summary>
  528. /// Gets or sets a collection that is used to generate the content of the control.
  529. /// </summary>
  530. public IEnumerable Items
  531. {
  532. get { return _items; }
  533. set { SetAndRaise(ItemsProperty, ref _items, value); }
  534. }
  535. public static readonly StyledProperty<bool> AreRowDetailsFrozenProperty =
  536. AvaloniaProperty.Register<DataGrid, bool>(nameof(AreRowDetailsFrozen));
  537. /// <summary>
  538. /// Gets or sets a value that indicates whether the row details sections remain
  539. /// fixed at the width of the display area or can scroll horizontally.
  540. /// </summary>
  541. public bool AreRowDetailsFrozen
  542. {
  543. get { return GetValue(AreRowDetailsFrozenProperty); }
  544. set { SetValue(AreRowDetailsFrozenProperty, value); }
  545. }
  546. public static readonly StyledProperty<IDataTemplate> RowDetailsTemplateProperty =
  547. AvaloniaProperty.Register<DataGrid, IDataTemplate>(nameof(RowDetailsTemplate));
  548. /// <summary>
  549. /// Gets or sets the template that is used to display the content of the details section of rows.
  550. /// </summary>
  551. public IDataTemplate RowDetailsTemplate
  552. {
  553. get { return GetValue(RowDetailsTemplateProperty); }
  554. set { SetValue(RowDetailsTemplateProperty, value); }
  555. }
  556. public static readonly StyledProperty<DataGridRowDetailsVisibilityMode> RowDetailsVisibilityModeProperty =
  557. AvaloniaProperty.Register<DataGrid, DataGridRowDetailsVisibilityMode>(nameof(RowDetailsVisibilityMode));
  558. /// <summary>
  559. /// Gets or sets a value that indicates when the details sections of rows are displayed.
  560. /// </summary>
  561. public DataGridRowDetailsVisibilityMode RowDetailsVisibilityMode
  562. {
  563. get { return GetValue(RowDetailsVisibilityModeProperty); }
  564. set { SetValue(RowDetailsVisibilityModeProperty, value); }
  565. }
  566. static DataGrid()
  567. {
  568. AffectsMeasure<DataGrid>(
  569. ColumnHeaderHeightProperty,
  570. HorizontalScrollBarVisibilityProperty,
  571. VerticalScrollBarVisibilityProperty);
  572. ItemsProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnItemsPropertyChanged(e));
  573. CanUserResizeColumnsProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnCanUserResizeColumnsChanged(e));
  574. ColumnWidthProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnColumnWidthChanged(e));
  575. RowBackgroundProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnRowBackgroundChanged(e));
  576. AlternatingRowBackgroundProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnRowBackgroundChanged(e));
  577. FrozenColumnCountProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnFrozenColumnCountChanged(e));
  578. GridLinesVisibilityProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnGridLinesVisibilityChanged(e));
  579. HeadersVisibilityProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnHeadersVisibilityChanged(e));
  580. HorizontalGridLinesBrushProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnHorizontalGridLinesBrushChanged(e));
  581. IsReadOnlyProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnIsReadOnlyChanged(e));
  582. MaxColumnWidthProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnMaxColumnWidthChanged(e));
  583. MinColumnWidthProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnMinColumnWidthChanged(e));
  584. RowHeightProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnRowHeightChanged(e));
  585. RowHeaderWidthProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnRowHeaderWidthChanged(e));
  586. SelectionModeProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnSelectionModeChanged(e));
  587. VerticalGridLinesBrushProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnVerticalGridLinesBrushChanged(e));
  588. SelectedIndexProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnSelectedIndexChanged(e));
  589. SelectedItemProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnSelectedItemChanged(e));
  590. IsEnabledProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.DataGrid_IsEnabledChanged(e));
  591. AreRowGroupHeadersFrozenProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnAreRowGroupHeadersFrozenChanged(e));
  592. RowDetailsTemplateProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnRowDetailsTemplateChanged(e));
  593. RowDetailsVisibilityModeProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnRowDetailsVisibilityModeChanged(e));
  594. AutoGenerateColumnsProperty.Changed.AddClassHandler<DataGrid>((x, e) => x.OnAutoGenerateColumnsChanged(e));
  595. }
  596. /// <summary>
  597. /// Initializes a new instance of the <see cref="T:Avalonia.Controls.DataGrid" /> class.
  598. /// </summary>
  599. public DataGrid()
  600. {
  601. KeyDown += DataGrid_KeyDown;
  602. KeyUp += DataGrid_KeyUp;
  603. //TODO: Check if override works
  604. GotFocus += DataGrid_GotFocus;
  605. LostFocus += DataGrid_LostFocus;
  606. _loadedRows = new List<DataGridRow>();
  607. _lostFocusActions = new Queue<Action>();
  608. _selectedItems = new DataGridSelectedItemsCollection(this);
  609. RowGroupHeadersTable = new IndexToValueTable<DataGridRowGroupInfo>();
  610. _bindingValidationErrors = new List<Exception>();
  611. DisplayData = new DataGridDisplayData(this);
  612. ColumnsInternal = CreateColumnsInstance();
  613. RowHeightEstimate = DATAGRID_defaultRowHeight;
  614. RowDetailsHeightEstimate = 0;
  615. _rowHeaderDesiredWidth = 0;
  616. DataConnection = new DataGridDataConnection(this);
  617. _showDetailsTable = new IndexToValueTable<bool>();
  618. _collapsedSlotsTable = new IndexToValueTable<bool>();
  619. AnchorSlot = -1;
  620. _lastEstimatedRow = -1;
  621. _editingColumnIndex = -1;
  622. _mouseOverRowIndex = null;
  623. CurrentCellCoordinates = new DataGridCellCoordinates(-1, -1);
  624. RowGroupHeaderHeightEstimate = DATAGRID_defaultRowHeight;
  625. }
  626. private void SetValueNoCallback<T>(AvaloniaProperty<T> property, T value, BindingPriority priority = BindingPriority.LocalValue)
  627. {
  628. _areHandlersSuspended = true;
  629. try
  630. {
  631. SetValue(property, value, priority);
  632. }
  633. finally
  634. {
  635. _areHandlersSuspended = false;
  636. }
  637. }
  638. private void OnRowDetailsVisibilityModeChanged(AvaloniaPropertyChangedEventArgs e)
  639. {
  640. UpdateRowDetailsVisibilityMode((DataGridRowDetailsVisibilityMode)e.NewValue);
  641. }
  642. private void OnRowDetailsTemplateChanged(AvaloniaPropertyChangedEventArgs e)
  643. {
  644. // Update the RowDetails templates if necessary
  645. if (_rowsPresenter != null)
  646. {
  647. foreach (DataGridRow row in GetAllRows())
  648. {
  649. if (GetRowDetailsVisibility(row.Index))
  650. {
  651. // DetailsPreferredHeight is initialized when the DetailsElement's size changes.
  652. row.ApplyDetailsTemplate(initializeDetailsPreferredHeight: false);
  653. }
  654. }
  655. }
  656. UpdateRowDetailsHeightEstimate();
  657. InvalidateMeasure();
  658. }
  659. /// <summary>
  660. /// ItemsProperty property changed handler.
  661. /// </summary>
  662. /// <param name="e">AvaloniaPropertyChangedEventArgs.</param>
  663. private void OnItemsPropertyChanged(AvaloniaPropertyChangedEventArgs e)
  664. {
  665. if (!_areHandlersSuspended)
  666. {
  667. Debug.Assert(DataConnection != null);
  668. var oldValue = (IEnumerable)e.OldValue;
  669. var newItemsSource = (IEnumerable)e.NewValue;
  670. if (LoadingOrUnloadingRow)
  671. {
  672. SetValueNoCallback(ItemsProperty, oldValue);
  673. throw DataGridError.DataGrid.CannotChangeItemsWhenLoadingRows();
  674. }
  675. // Try to commit edit on the old DataSource, but force a cancel if it fails
  676. if (!CommitEdit())
  677. {
  678. CancelEdit(DataGridEditingUnit.Row, false);
  679. }
  680. DataConnection.UnWireEvents(DataConnection.DataSource);
  681. DataConnection.ClearDataProperties();
  682. ClearRowGroupHeadersTable();
  683. // The old selected indexes are no longer relevant. There's a perf benefit from
  684. // updating the selected indexes with a null DataSource, because we know that all
  685. // of the previously selected indexes have been removed from selection
  686. DataConnection.DataSource = null;
  687. _selectedItems.UpdateIndexes();
  688. CoerceSelectedItem();
  689. // Wrap an IEnumerable in an ICollectionView if it's not already one
  690. bool setDefaultSelection = false;
  691. if (newItemsSource != null && !(newItemsSource is IDataGridCollectionView))
  692. {
  693. DataConnection.DataSource = DataGridDataConnection.CreateView(newItemsSource);
  694. }
  695. else
  696. {
  697. DataConnection.DataSource = newItemsSource;
  698. setDefaultSelection = true;
  699. }
  700. if (DataConnection.DataSource != null)
  701. {
  702. // Setup the column headers
  703. if (DataConnection.DataType != null)
  704. {
  705. foreach (var column in ColumnsInternal.GetDisplayedColumns())
  706. {
  707. if (column is DataGridBoundColumn boundColumn)
  708. {
  709. boundColumn.SetHeaderFromBinding();
  710. }
  711. }
  712. }
  713. DataConnection.WireEvents(DataConnection.DataSource);
  714. }
  715. // Wait for the current cell to be set before we raise any SelectionChanged events
  716. _makeFirstDisplayedCellCurrentCellPending = true;
  717. // Clear out the old rows and remove the generated columns
  718. ClearRows(false); //recycle
  719. RemoveAutoGeneratedColumns();
  720. // Set the SlotCount (from the data count and number of row group headers) before we make the default selection
  721. PopulateRowGroupHeadersTable();
  722. SelectedItem = null;
  723. if (DataConnection.CollectionView != null && setDefaultSelection)
  724. {
  725. SelectedItem = DataConnection.CollectionView.CurrentItem;
  726. }
  727. // Treat this like the DataGrid has never been measured because all calculations at
  728. // this point are invalid until the next layout cycle. For instance, the ItemsSource
  729. // can be set when the DataGrid is not part of the visual tree
  730. _measured = false;
  731. InvalidateMeasure();
  732. }
  733. }
  734. private void OnSelectedIndexChanged(AvaloniaPropertyChangedEventArgs e)
  735. {
  736. if (!_areHandlersSuspended)
  737. {
  738. int index = (int)e.NewValue;
  739. // GetDataItem returns null if index is >= Count, we do not check newValue
  740. // against Count here to avoid enumerating through an Enumerable twice
  741. // Setting SelectedItem coerces the finally value of the SelectedIndex
  742. object newSelectedItem = (index < 0) ? null : DataConnection.GetDataItem(index);
  743. SelectedItem = newSelectedItem;
  744. if (SelectedItem != newSelectedItem)
  745. {
  746. SetValueNoCallback(SelectedIndexProperty, (int)e.OldValue);
  747. }
  748. }
  749. }
  750. private void OnSelectedItemChanged(AvaloniaPropertyChangedEventArgs e)
  751. {
  752. if (!_areHandlersSuspended)
  753. {
  754. int rowIndex = (e.NewValue == null) ? -1 : DataConnection.IndexOf(e.NewValue);
  755. if (rowIndex == -1)
  756. {
  757. // If the Item is null or it's not found, clear the Selection
  758. if (!CommitEdit(DataGridEditingUnit.Row, exitEditingMode: true))
  759. {
  760. // Edited value couldn't be committed or aborted
  761. SetValueNoCallback(SelectedItemProperty, e.OldValue);
  762. return;
  763. }
  764. // Clear all row selections
  765. ClearRowSelection(resetAnchorSlot: true);
  766. }
  767. else
  768. {
  769. int slot = SlotFromRowIndex(rowIndex);
  770. if (slot != CurrentSlot)
  771. {
  772. if (!CommitEdit(DataGridEditingUnit.Row, exitEditingMode: true))
  773. {
  774. // Edited value couldn't be committed or aborted
  775. SetValueNoCallback(SelectedItemProperty, e.OldValue);
  776. return;
  777. }
  778. if (slot >= SlotCount || slot < -1)
  779. {
  780. if (DataConnection.CollectionView != null)
  781. {
  782. DataConnection.CollectionView.MoveCurrentToPosition(rowIndex);
  783. }
  784. }
  785. }
  786. int oldSelectedIndex = SelectedIndex;
  787. SetValueNoCallback(SelectedIndexProperty, rowIndex);
  788. try
  789. {
  790. _noSelectionChangeCount++;
  791. int columnIndex = CurrentColumnIndex;
  792. if (columnIndex == -1)
  793. {
  794. columnIndex = FirstDisplayedNonFillerColumnIndex;
  795. }
  796. if (IsSlotOutOfSelectionBounds(slot))
  797. {
  798. ClearRowSelection(slotException: slot, setAnchorSlot: true);
  799. return;
  800. }
  801. UpdateSelectionAndCurrency(columnIndex, slot, DataGridSelectionAction.SelectCurrent, scrollIntoView: false);
  802. }
  803. finally
  804. {
  805. NoSelectionChangeCount--;
  806. }
  807. if (!_successfullyUpdatedSelection)
  808. {
  809. SetValueNoCallback(SelectedIndexProperty, oldSelectedIndex);
  810. SetValueNoCallback(SelectedItemProperty, e.OldValue);
  811. }
  812. }
  813. }
  814. }
  815. private void OnVerticalGridLinesBrushChanged(AvaloniaPropertyChangedEventArgs e)
  816. {
  817. if (_rowsPresenter != null)
  818. {
  819. foreach (DataGridRow row in GetAllRows())
  820. {
  821. row.EnsureGridLines();
  822. }
  823. }
  824. }
  825. private void OnSelectionModeChanged(AvaloniaPropertyChangedEventArgs e)
  826. {
  827. if (!_areHandlersSuspended)
  828. {
  829. ClearRowSelection(resetAnchorSlot: true);
  830. }
  831. }
  832. private void OnRowHeaderWidthChanged(AvaloniaPropertyChangedEventArgs e)
  833. {
  834. if (!_areHandlersSuspended)
  835. {
  836. EnsureRowHeaderWidth();
  837. }
  838. }
  839. private void OnRowHeightChanged(AvaloniaPropertyChangedEventArgs e)
  840. {
  841. if (!_areHandlersSuspended)
  842. {
  843. InvalidateRowHeightEstimate();
  844. // Re-measure all the rows due to the Height change
  845. InvalidateRowsMeasure(invalidateIndividualElements: true);
  846. // DataGrid needs to update the layout information and the ScrollBars
  847. InvalidateMeasure();
  848. }
  849. }
  850. private void OnMinColumnWidthChanged(AvaloniaPropertyChangedEventArgs e)
  851. {
  852. if (!_areHandlersSuspended)
  853. {
  854. double oldValue = (double)e.OldValue;
  855. foreach (DataGridColumn column in ColumnsInternal.GetDisplayedColumns())
  856. {
  857. OnColumnMinWidthChanged(column, Math.Max(column.MinWidth, oldValue));
  858. }
  859. }
  860. }
  861. private void OnMaxColumnWidthChanged(AvaloniaPropertyChangedEventArgs e)
  862. {
  863. if (!_areHandlersSuspended)
  864. {
  865. var oldValue = (double)e.OldValue;
  866. foreach (DataGridColumn column in ColumnsInternal.GetDisplayedColumns())
  867. {
  868. OnColumnMaxWidthChanged(column, Math.Min(column.MaxWidth, oldValue));
  869. }
  870. }
  871. }
  872. private void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
  873. {
  874. if (!_areHandlersSuspended)
  875. {
  876. var value = (bool)e.NewValue;
  877. if (value && !CommitEdit(DataGridEditingUnit.Row, exitEditingMode: true))
  878. {
  879. CancelEdit(DataGridEditingUnit.Row, raiseEvents: false);
  880. }
  881. }
  882. }
  883. private void OnHorizontalGridLinesBrushChanged(AvaloniaPropertyChangedEventArgs e)
  884. {
  885. if (!_areHandlersSuspended && _rowsPresenter != null)
  886. {
  887. foreach (DataGridRow row in GetAllRows())
  888. {
  889. row.EnsureGridLines();
  890. }
  891. }
  892. }
  893. private void OnHeadersVisibilityChanged(AvaloniaPropertyChangedEventArgs e)
  894. {
  895. var oldValue = (DataGridHeadersVisibility)e.OldValue;
  896. var newValue = (DataGridHeadersVisibility)e.NewValue;
  897. bool hasFlags(DataGridHeadersVisibility value, DataGridHeadersVisibility flags) => ((value & flags) == flags);
  898. bool newValueCols = hasFlags(newValue, DataGridHeadersVisibility.Column);
  899. bool newValueRows = hasFlags(newValue, DataGridHeadersVisibility.Row);
  900. bool oldValueCols = hasFlags(oldValue, DataGridHeadersVisibility.Column);
  901. bool oldValueRows = hasFlags(oldValue, DataGridHeadersVisibility.Row);
  902. // Columns
  903. if (newValueCols != oldValueCols)
  904. {
  905. if (_columnHeadersPresenter != null)
  906. {
  907. EnsureColumnHeadersVisibility();
  908. if (!newValueCols)
  909. {
  910. _columnHeadersPresenter.Measure(Size.Empty);
  911. }
  912. else
  913. {
  914. EnsureVerticalGridLines();
  915. }
  916. InvalidateMeasure();
  917. }
  918. }
  919. // Rows
  920. if (newValueRows != oldValueRows)
  921. {
  922. if (_rowsPresenter != null)
  923. {
  924. foreach (Control element in _rowsPresenter.Children)
  925. {
  926. if (element is DataGridRow row)
  927. {
  928. row.EnsureHeaderStyleAndVisibility(null);
  929. if (newValueRows)
  930. {
  931. row.UpdatePseudoClasses();
  932. row.EnsureHeaderVisibility();
  933. }
  934. }
  935. else if (element is DataGridRowGroupHeader rowGroupHeader)
  936. {
  937. rowGroupHeader.EnsureHeaderVisibility();
  938. }
  939. }
  940. InvalidateRowHeightEstimate();
  941. InvalidateRowsMeasure(invalidateIndividualElements: true);
  942. }
  943. }
  944. if (_topLeftCornerHeader != null)
  945. {
  946. _topLeftCornerHeader.IsVisible = newValueRows && newValueCols;
  947. if (_topLeftCornerHeader.IsVisible)
  948. {
  949. _topLeftCornerHeader.Measure(Size.Empty);
  950. }
  951. }
  952. }
  953. private void OnGridLinesVisibilityChanged(AvaloniaPropertyChangedEventArgs e)
  954. {
  955. foreach (DataGridRow row in GetAllRows())
  956. {
  957. row.EnsureGridLines();
  958. row.InvalidateHorizontalArrange();
  959. }
  960. }
  961. private void OnFrozenColumnCountChanged(AvaloniaPropertyChangedEventArgs e)
  962. {
  963. ProcessFrozenColumnCount();
  964. }
  965. private void ProcessFrozenColumnCount()
  966. {
  967. CorrectColumnFrozenStates();
  968. ComputeScrollBarsLayout();
  969. InvalidateColumnHeadersArrange();
  970. InvalidateCellsArrange();
  971. }
  972. private void OnRowBackgroundChanged(AvaloniaPropertyChangedEventArgs e)
  973. {
  974. foreach (DataGridRow row in GetAllRows())
  975. {
  976. row.EnsureBackground();
  977. }
  978. }
  979. private void OnColumnWidthChanged(AvaloniaPropertyChangedEventArgs e)
  980. {
  981. var value = (DataGridLength)e.NewValue;
  982. foreach (DataGridColumn column in ColumnsInternal.GetDisplayedColumns())
  983. {
  984. if (column.InheritsWidth)
  985. {
  986. column.SetWidthInternalNoCallback(value);
  987. }
  988. }
  989. EnsureHorizontalLayout();
  990. }
  991. private void OnCanUserResizeColumnsChanged(AvaloniaPropertyChangedEventArgs e)
  992. {
  993. EnsureHorizontalLayout();
  994. }
  995. /// <summary>
  996. /// Occurs one time for each public, non-static property in the bound data type when the
  997. /// <see cref="P:Avalonia.Controls.DataGrid.ItemsSource" /> property is changed and the
  998. /// <see cref="P:Avalonia.Controls.DataGrid.AutoGenerateColumns" /> property is true.
  999. /// </summary>
  1000. public event EventHandler<DataGridAutoGeneratingColumnEventArgs> AutoGeneratingColumn;
  1001. /// <summary>
  1002. /// Occurs before a cell or row enters editing mode.
  1003. /// </summary>
  1004. public event EventHandler<DataGridBeginningEditEventArgs> BeginningEdit;
  1005. /// <summary>
  1006. /// Occurs after cell editing has ended.
  1007. /// </summary>
  1008. public event EventHandler<DataGridCellEditEndedEventArgs> CellEditEnded;
  1009. /// <summary>
  1010. /// Occurs immediately before cell editing has ended.
  1011. /// </summary>
  1012. public event EventHandler<DataGridCellEditEndingEventArgs> CellEditEnding;
  1013. /// <summary>
  1014. /// Occurs when cell is mouse-pressed.
  1015. /// </summary>
  1016. public event EventHandler<DataGridCellPointerPressedEventArgs> CellPointerPressed;
  1017. /// <summary>
  1018. /// Occurs when the <see cref="P:Avalonia.Controls.DataGridColumn.DisplayIndex" />
  1019. /// property of a column changes.
  1020. /// </summary>
  1021. public event EventHandler<DataGridColumnEventArgs> ColumnDisplayIndexChanged;
  1022. /// <summary>
  1023. /// Raised when column reordering ends, to allow subscribers to clean up.
  1024. /// </summary>
  1025. public event EventHandler<DataGridColumnEventArgs> ColumnReordered;
  1026. /// <summary>
  1027. /// Raised when starting a column reordering action. Subscribers to this event can
  1028. /// set tooltip and caret UIElements, constrain tooltip position, indicate that
  1029. /// a preview should be shown, or cancel reordering.
  1030. /// </summary>
  1031. public event EventHandler<DataGridColumnReorderingEventArgs> ColumnReordering;
  1032. /// <summary>
  1033. /// Occurs when a different cell becomes the current cell.
  1034. /// </summary>
  1035. public event EventHandler<EventArgs> CurrentCellChanged;
  1036. /// <summary>
  1037. /// Occurs after a <see cref="T:Avalonia.Controls.DataGridRow" />
  1038. /// is instantiated, so that you can customize it before it is used.
  1039. /// </summary>
  1040. public event EventHandler<DataGridRowEventArgs> LoadingRow;
  1041. /// <summary>
  1042. /// Occurs when a cell in a <see cref="T:Avalonia.Controls.DataGridTemplateColumn" /> enters editing mode.
  1043. ///
  1044. /// </summary>
  1045. public event EventHandler<DataGridPreparingCellForEditEventArgs> PreparingCellForEdit;
  1046. /// <summary>
  1047. /// Occurs when the row has been successfully committed or cancelled.
  1048. /// </summary>
  1049. public event EventHandler<DataGridRowEditEndedEventArgs> RowEditEnded;
  1050. /// <summary>
  1051. /// Occurs immediately before the row has been successfully committed or cancelled.
  1052. /// </summary>
  1053. public event EventHandler<DataGridRowEditEndingEventArgs> RowEditEnding;
  1054. public static readonly RoutedEvent<SelectionChangedEventArgs> SelectionChangedEvent =
  1055. RoutedEvent.Register<DataGrid, SelectionChangedEventArgs>(nameof(SelectionChanged), RoutingStrategies.Bubble);
  1056. /// <summary>
  1057. /// Occurs when the <see cref="P:Avalonia.Controls.DataGrid.SelectedItem" /> or
  1058. /// <see cref="P:Avalonia.Controls.DataGrid.SelectedItems" /> property value changes.
  1059. /// </summary>
  1060. public event EventHandler<SelectionChangedEventArgs> SelectionChanged
  1061. {
  1062. add { AddHandler(SelectionChangedEvent, value); }
  1063. remove { AddHandler(SelectionChangedEvent, value); }
  1064. }
  1065. /// <summary>
  1066. /// Occurs when a <see cref="T:Avalonia.Controls.DataGridRow" />
  1067. /// object becomes available for reuse.
  1068. /// </summary>
  1069. public event EventHandler<DataGridRowEventArgs> UnloadingRow;
  1070. /// <summary>
  1071. /// Occurs when a new row details template is applied to a row, so that you can customize
  1072. /// the details section before it is used.
  1073. /// </summary>
  1074. public event EventHandler<DataGridRowDetailsEventArgs> LoadingRowDetails;
  1075. /// <summary>
  1076. /// Occurs when the <see cref="P:Avalonia.Controls.DataGrid.RowDetailsVisibilityMode" />
  1077. /// property value changes.
  1078. /// </summary>
  1079. public event EventHandler<DataGridRowDetailsEventArgs> RowDetailsVisibilityChanged;
  1080. /// <summary>
  1081. /// Occurs when a row details element becomes available for reuse.
  1082. /// </summary>
  1083. public event EventHandler<DataGridRowDetailsEventArgs> UnloadingRowDetails;
  1084. /// <summary>
  1085. /// Gets a collection that contains all the columns in the control.
  1086. /// </summary>
  1087. public ObservableCollection<DataGridColumn> Columns
  1088. {
  1089. get
  1090. {
  1091. // we use a backing field here because the field's type
  1092. // is a subclass of the property's
  1093. return ColumnsInternal;
  1094. }
  1095. }
  1096. /// <summary>
  1097. /// Gets or sets the column that contains the current cell.
  1098. /// </summary>
  1099. public DataGridColumn CurrentColumn
  1100. {
  1101. get
  1102. {
  1103. if (CurrentColumnIndex == -1)
  1104. {
  1105. return null;
  1106. }
  1107. Debug.Assert(CurrentColumnIndex < ColumnsItemsInternal.Count);
  1108. return ColumnsItemsInternal[CurrentColumnIndex];
  1109. }
  1110. set
  1111. {
  1112. DataGridColumn dataGridColumn = value;
  1113. if (dataGridColumn == null)
  1114. {
  1115. throw DataGridError.DataGrid.ValueCannotBeSetToNull("value", "CurrentColumn");
  1116. }
  1117. if (CurrentColumn != dataGridColumn)
  1118. {
  1119. if (dataGridColumn.OwningGrid != this)
  1120. {
  1121. // Provided column does not belong to this DataGrid
  1122. throw DataGridError.DataGrid.ColumnNotInThisDataGrid();
  1123. }
  1124. if (!dataGridColumn.IsVisible)
  1125. {
  1126. // CurrentColumn cannot be set to an invisible column
  1127. throw DataGridError.DataGrid.ColumnCannotBeCollapsed();
  1128. }
  1129. if (CurrentSlot == -1)
  1130. {
  1131. // There is no current row so the current column cannot be set
  1132. throw DataGridError.DataGrid.NoCurrentRow();
  1133. }
  1134. bool beginEdit = _editingColumnIndex != -1;
  1135. //exitEditingMode, keepFocus, raiseEvents
  1136. if (!EndCellEdit(DataGridEditAction.Commit, true, ContainsFocus, true))
  1137. {
  1138. // Edited value couldn't be committed or aborted
  1139. return;
  1140. }
  1141. UpdateSelectionAndCurrency(dataGridColumn.Index, CurrentSlot, DataGridSelectionAction.None, false); //scrollIntoView
  1142. Debug.Assert(_successfullyUpdatedSelection);
  1143. if (beginEdit &&
  1144. _editingColumnIndex == -1 &&
  1145. CurrentSlot != -1 &&
  1146. CurrentColumnIndex != -1 &&
  1147. CurrentColumnIndex == dataGridColumn.Index &&
  1148. dataGridColumn.OwningGrid == this &&
  1149. !GetColumnEffectiveReadOnlyState(dataGridColumn))
  1150. {
  1151. // Returning to editing mode since the grid was in that mode prior to the EndCellEdit call above.
  1152. BeginCellEdit(new RoutedEventArgs());
  1153. }
  1154. }
  1155. }
  1156. }
  1157. /// <summary>
  1158. /// Gets a list that contains the data items corresponding to the selected rows.
  1159. /// </summary>
  1160. public IList SelectedItems
  1161. {
  1162. get { return _selectedItems as IList; }
  1163. }
  1164. internal DataGridColumnCollection ColumnsInternal
  1165. {
  1166. get;
  1167. private set;
  1168. }
  1169. internal int AnchorSlot
  1170. {
  1171. get;
  1172. private set;
  1173. }
  1174. internal double ActualRowHeaderWidth
  1175. {
  1176. get
  1177. {
  1178. if (!AreRowHeadersVisible)
  1179. {
  1180. return 0;
  1181. }
  1182. else
  1183. {
  1184. return !double.IsNaN(RowHeaderWidth) ? RowHeaderWidth : RowHeadersDesiredWidth;
  1185. }
  1186. }
  1187. }
  1188. internal double ActualRowsPresenterHeight
  1189. {
  1190. get
  1191. {
  1192. if (_rowsPresenter != null)
  1193. {
  1194. return _rowsPresenter.Bounds.Height;
  1195. }
  1196. return 0;
  1197. }
  1198. }
  1199. internal bool AreColumnHeadersVisible
  1200. {
  1201. get
  1202. {
  1203. return (HeadersVisibility & DataGridHeadersVisibility.Column) == DataGridHeadersVisibility.Column;
  1204. }
  1205. }
  1206. internal bool AreRowHeadersVisible
  1207. {
  1208. get
  1209. {
  1210. return (HeadersVisibility & DataGridHeadersVisibility.Row) == DataGridHeadersVisibility.Row;
  1211. }
  1212. }
  1213. /// <summary>
  1214. /// Indicates whether or not at least one auto-sizing column is waiting for all the rows
  1215. /// to be measured before its final width is determined.
  1216. /// </summary>
  1217. internal bool AutoSizingColumns
  1218. {
  1219. get
  1220. {
  1221. return _autoSizingColumns;
  1222. }
  1223. set
  1224. {
  1225. if (_autoSizingColumns && !value && ColumnsInternal != null)
  1226. {
  1227. double adjustment = CellsWidth - ColumnsInternal.VisibleEdgedColumnsWidth;
  1228. AdjustColumnWidths(0, adjustment, false);
  1229. foreach (DataGridColumn column in ColumnsInternal.GetVisibleColumns())
  1230. {
  1231. column.IsInitialDesiredWidthDetermined = true;
  1232. }
  1233. ColumnsInternal.EnsureVisibleEdgedColumnsWidth();
  1234. ComputeScrollBarsLayout();
  1235. InvalidateColumnHeadersMeasure();
  1236. InvalidateRowsMeasure(true);
  1237. }
  1238. _autoSizingColumns = value;
  1239. }
  1240. }
  1241. internal double AvailableSlotElementRoom
  1242. {
  1243. get;
  1244. set;
  1245. }
  1246. // Height currently available for cells this value is smaller. This height is reduced by the existence of ColumnHeaders
  1247. // or a horizontal scrollbar. Layout is asynchronous so changes to the ColumnHeaders or the horizontal scrollbar are
  1248. // not reflected immediately.
  1249. internal double CellsHeight
  1250. {
  1251. get
  1252. {
  1253. return RowsPresenterEstimatedAvailableHeight ?? 0;
  1254. }
  1255. }
  1256. // Width currently available for cells this value is smaller. This width is reduced by the existence of RowHeaders
  1257. // or a vertical scrollbar. Layout is asynchronous so changes to the RowHeaders or the vertical scrollbar are
  1258. // not reflected immediately
  1259. internal double CellsWidth
  1260. {
  1261. get
  1262. {
  1263. double rowsWidth = double.PositiveInfinity;
  1264. if (RowsPresenterAvailableSize.HasValue)
  1265. {
  1266. rowsWidth = Math.Max(0, RowsPresenterAvailableSize.Value.Width - ActualRowHeaderWidth);
  1267. }
  1268. return double.IsPositiveInfinity(rowsWidth) ? ColumnsInternal.VisibleEdgedColumnsWidth : rowsWidth;
  1269. }
  1270. }
  1271. internal DataGridColumnHeadersPresenter ColumnHeaders => _columnHeadersPresenter;
  1272. internal List<DataGridColumn> ColumnsItemsInternal => ColumnsInternal.ItemsInternal;
  1273. internal bool ContainsFocus
  1274. {
  1275. get;
  1276. private set;
  1277. }
  1278. internal int CurrentColumnIndex
  1279. {
  1280. get
  1281. {
  1282. return CurrentCellCoordinates.ColumnIndex;
  1283. }
  1284. private set
  1285. {
  1286. CurrentCellCoordinates.ColumnIndex = value;
  1287. }
  1288. }
  1289. internal int CurrentSlot
  1290. {
  1291. get
  1292. {
  1293. return CurrentCellCoordinates.Slot;
  1294. }
  1295. private set
  1296. {
  1297. CurrentCellCoordinates.Slot = value;
  1298. }
  1299. }
  1300. internal DataGridDataConnection DataConnection
  1301. {
  1302. get;
  1303. private set;
  1304. }
  1305. internal DataGridDisplayData DisplayData
  1306. {
  1307. get;
  1308. private set;
  1309. }
  1310. internal int EditingColumnIndex
  1311. {
  1312. get;
  1313. private set;
  1314. }
  1315. internal DataGridRow EditingRow
  1316. {
  1317. get;
  1318. private set;
  1319. }
  1320. internal double FirstDisplayedScrollingColumnHiddenWidth => _negHorizontalOffset;
  1321. // When the RowsPresenter's width increases, the HorizontalOffset will be incorrect until
  1322. // the scrollbar's layout is recalculated, which doesn't occur until after the cells are measured.
  1323. // This property exists to account for this scenario, and avoid collapsing the incorrect cells.
  1324. internal double HorizontalAdjustment
  1325. {
  1326. get;
  1327. private set;
  1328. }
  1329. internal static double HorizontalGridLinesThickness => DATAGRID_horizontalGridLinesThickness;
  1330. // the sum of the widths in pixels of the scrolling columns preceding
  1331. // the first displayed scrolling column
  1332. internal double HorizontalOffset
  1333. {
  1334. get
  1335. {
  1336. return _horizontalOffset;
  1337. }
  1338. set
  1339. {
  1340. if (value < 0)
  1341. {
  1342. value = 0;
  1343. }
  1344. double widthNotVisible = Math.Max(0, ColumnsInternal.VisibleEdgedColumnsWidth - CellsWidth);
  1345. if (value > widthNotVisible)
  1346. {
  1347. value = widthNotVisible;
  1348. }
  1349. if (value == _horizontalOffset)
  1350. {
  1351. return;
  1352. }
  1353. if (_hScrollBar != null && value != _hScrollBar.Value)
  1354. {
  1355. _hScrollBar.Value = value;
  1356. }
  1357. _horizontalOffset = value;
  1358. DisplayData.FirstDisplayedScrollingCol = ComputeFirstVisibleScrollingColumn();
  1359. // update the lastTotallyDisplayedScrollingCol
  1360. ComputeDisplayedColumns();
  1361. }
  1362. }
  1363. internal ScrollBar HorizontalScrollBar => _hScrollBar;
  1364. internal IndexToValueTable<DataGridRowGroupInfo> RowGroupHeadersTable
  1365. {
  1366. get;
  1367. private set;
  1368. }
  1369. internal bool LoadingOrUnloadingRow
  1370. {
  1371. get;
  1372. private set;
  1373. }
  1374. internal bool InDisplayIndexAdjustments
  1375. {
  1376. get;
  1377. set;
  1378. }
  1379. internal int? MouseOverRowIndex
  1380. {
  1381. get
  1382. {
  1383. return _mouseOverRowIndex;
  1384. }
  1385. set
  1386. {
  1387. if (_mouseOverRowIndex != value)
  1388. {
  1389. DataGridRow oldMouseOverRow = null;
  1390. if (_mouseOverRowIndex.HasValue)
  1391. {
  1392. int oldSlot = SlotFromRowIndex(_mouseOverRowIndex.Value);
  1393. if (IsSlotVisible(oldSlot))
  1394. {
  1395. oldMouseOverRow = DisplayData.GetDisplayedElement(oldSlot) as DataGridRow;
  1396. }
  1397. }
  1398. _mouseOverRowIndex = value;
  1399. // State for the old row needs to be applied after setting the new value
  1400. if (oldMouseOverRow != null)
  1401. {
  1402. oldMouseOverRow.UpdatePseudoClasses();
  1403. }
  1404. if (_mouseOverRowIndex.HasValue)
  1405. {
  1406. int newSlot = SlotFromRowIndex(_mouseOverRowIndex.Value);
  1407. if (IsSlotVisible(newSlot))
  1408. {
  1409. DataGridRow newMouseOverRow = DisplayData.GetDisplayedElement(newSlot) as DataGridRow;
  1410. Debug.Assert(newMouseOverRow != null);
  1411. if (newMouseOverRow != null)
  1412. {
  1413. newMouseOverRow.UpdatePseudoClasses();
  1414. }
  1415. }
  1416. }
  1417. }
  1418. }
  1419. }
  1420. internal double NegVerticalOffset
  1421. {
  1422. get;
  1423. private set;
  1424. }
  1425. internal int NoCurrentCellChangeCount
  1426. {
  1427. get
  1428. {
  1429. return _noCurrentCellChangeCount;
  1430. }
  1431. set
  1432. {
  1433. _noCurrentCellChangeCount = value;
  1434. if (value == 0)
  1435. {
  1436. FlushCurrentCellChanged();
  1437. }
  1438. }
  1439. }
  1440. internal double RowDetailsHeightEstimate
  1441. {
  1442. get;
  1443. private set;
  1444. }
  1445. internal double RowHeadersDesiredWidth
  1446. {
  1447. get
  1448. {
  1449. return _rowHeaderDesiredWidth;
  1450. }
  1451. set
  1452. {
  1453. // We only auto grow
  1454. if (_rowHeaderDesiredWidth < value)
  1455. {
  1456. double oldActualRowHeaderWidth = ActualRowHeaderWidth;
  1457. _rowHeaderDesiredWidth = value;
  1458. if (oldActualRowHeaderWidth != ActualRowHeaderWidth)
  1459. {
  1460. EnsureRowHeaderWidth();
  1461. }
  1462. }
  1463. }
  1464. }
  1465. internal double RowGroupHeaderHeightEstimate
  1466. {
  1467. get;
  1468. private set;
  1469. }
  1470. internal double RowHeightEstimate
  1471. {
  1472. get;
  1473. private set;
  1474. }
  1475. internal Size? RowsPresenterAvailableSize
  1476. {
  1477. get
  1478. {
  1479. return _rowsPresenterAvailableSize;
  1480. }
  1481. set
  1482. {
  1483. if (_rowsPresenterAvailableSize.HasValue && value.HasValue && value.Value.Width > RowsPresenterAvailableSize.Value.Width)
  1484. {
  1485. // When the available cells width increases, the horizontal offset can be incorrect.
  1486. // Store away an adjustment to use during the CellsPresenter's measure, so that the
  1487. // ShouldDisplayCell method correctly determines if a cell will be in view.
  1488. //
  1489. // | h. offset | new available cells width |
  1490. // |-------------->|----------------------------------------->|
  1491. // __________________________________________________ |
  1492. // | | | | | |
  1493. // | column0 | column1 | column2 | column3 |<----->|
  1494. // | | | | | adj. |
  1495. //
  1496. double adjustment = (_horizontalOffset + value.Value.Width) - ColumnsInternal.VisibleEdgedColumnsWidth;
  1497. HorizontalAdjustment = Math.Min(HorizontalOffset, Math.Max(0, adjustment));
  1498. }
  1499. else
  1500. {
  1501. HorizontalAdjustment = 0;
  1502. }
  1503. _rowsPresenterAvailableSize = value;
  1504. }
  1505. }
  1506. internal double? RowsPresenterEstimatedAvailableHeight
  1507. {
  1508. get;
  1509. set;
  1510. }
  1511. internal double[] RowGroupSublevelIndents
  1512. {
  1513. get;
  1514. private set;
  1515. }
  1516. // This flag indicates whether selection has actually changed during a selection operation,
  1517. // and exists to ensure that FlushSelectionChanged doesn't unnecessarily raise SelectionChanged.
  1518. internal bool SelectionHasChanged
  1519. {
  1520. get;
  1521. set;
  1522. }
  1523. internal int SlotCount
  1524. {
  1525. get;
  1526. private set;
  1527. }
  1528. internal bool UpdatedStateOnMouseLeftButtonDown
  1529. {
  1530. get;
  1531. set;
  1532. }
  1533. /// <summary>
  1534. /// Indicates whether or not to use star-sizing logic. If the DataGrid has infinite available space,
  1535. /// then star sizing doesn't make sense. In this case, all star columns grow to a predefined size of
  1536. /// 10,000 pixels in order to show the developer that star columns shouldn't be used.
  1537. /// </summary>
  1538. internal bool UsesStarSizing
  1539. {
  1540. get
  1541. {
  1542. if (ColumnsInternal != null)
  1543. {
  1544. return ColumnsInternal.VisibleStarColumnCount > 0 &&
  1545. (!RowsPresenterAvailableSize.HasValue || !double.IsPositiveInfinity(RowsPresenterAvailableSize.Value.Width));
  1546. }
  1547. return false;
  1548. }
  1549. }
  1550. internal ScrollBar VerticalScrollBar => _vScrollBar;
  1551. internal int VisibleSlotCount
  1552. {
  1553. get;
  1554. set;
  1555. }
  1556. /// <summary>
  1557. /// Gets the data item bound to the row that contains the current cell.
  1558. /// </summary>
  1559. protected object CurrentItem
  1560. {
  1561. get
  1562. {
  1563. if (CurrentSlot == -1 || Items == null || RowGroupHeadersTable.Contains(CurrentSlot))
  1564. {
  1565. return null;
  1566. }
  1567. return DataConnection.GetDataItem(RowIndexFromSlot(CurrentSlot));
  1568. }
  1569. }
  1570. private DataGridCellCoordinates CurrentCellCoordinates
  1571. {
  1572. get;
  1573. set;
  1574. }
  1575. private int FirstDisplayedNonFillerColumnIndex
  1576. {
  1577. get
  1578. {
  1579. DataGridColumn column = ColumnsInternal.FirstVisibleNonFillerColumn;
  1580. if (column != null)
  1581. {
  1582. if (column.IsFrozen)
  1583. {
  1584. return column.Index;
  1585. }
  1586. else
  1587. {
  1588. if (DisplayData.FirstDisplayedScrollingCol >= column.Index)
  1589. {
  1590. return DisplayData.FirstDisplayedScrollingCol;
  1591. }
  1592. else
  1593. {
  1594. return column.Index;
  1595. }
  1596. }
  1597. }
  1598. return -1;
  1599. }
  1600. }
  1601. private int NoSelectionChangeCount
  1602. {
  1603. get
  1604. {
  1605. return _noSelectionChangeCount;
  1606. }
  1607. set
  1608. {
  1609. _noSelectionChangeCount = value;
  1610. if (value == 0)
  1611. {
  1612. FlushSelectionChanged();
  1613. }
  1614. }
  1615. }
  1616. /// <summary>
  1617. /// Enters editing mode for the current cell and current row (if they're not already in editing mode).
  1618. /// </summary>
  1619. /// <returns>True if operation was successful. False otherwise.</returns>
  1620. public bool BeginEdit()
  1621. {
  1622. return BeginEdit(null);
  1623. }
  1624. /// <summary>
  1625. /// Enters editing mode for the current cell and current row (if they're not already in editing mode).
  1626. /// </summary>
  1627. /// <param name="editingEventArgs">Provides information about the user gesture that caused the call to BeginEdit. Can be null.</param>
  1628. /// <returns>True if operation was successful. False otherwise.</returns>
  1629. public bool BeginEdit(RoutedEventArgs editingEventArgs)
  1630. {
  1631. if (CurrentColumnIndex == -1 || !GetRowSelection(CurrentSlot))
  1632. {
  1633. return false;
  1634. }
  1635. Debug.Assert(CurrentColumnIndex >= 0);
  1636. Debug.Assert(CurrentColumnIndex < ColumnsItemsInternal.Count);
  1637. Debug.Assert(CurrentSlot >= -1);
  1638. Debug.Assert(CurrentSlot < SlotCount);
  1639. Debug.Assert(EditingRow == null || EditingRow.Slot == CurrentSlot);
  1640. if (GetColumnEffectiveReadOnlyState(CurrentColumn))
  1641. {
  1642. // Current column is read-only
  1643. return false;
  1644. }
  1645. return BeginCellEdit(editingEventArgs);
  1646. }
  1647. /// <summary>
  1648. /// Cancels editing mode and restores the original value.
  1649. /// </summary>
  1650. /// <returns>True if operation was successful. False otherwise.</returns>
  1651. public bool CancelEdit()
  1652. {
  1653. return CancelEdit(DataGridEditingUnit.Row);
  1654. }
  1655. /// <summary>
  1656. /// Cancels editing mode for the specified DataGridEditingUnit and restores its original value.
  1657. /// </summary>
  1658. /// <param name="editingUnit">Specifies whether to cancel edit for a Cell or Row.</param>
  1659. /// <returns>True if operation was successful. False otherwise.</returns>
  1660. public bool CancelEdit(DataGridEditingUnit editingUnit)
  1661. {
  1662. return CancelEdit(editingUnit, raiseEvents: true);
  1663. }
  1664. /// <summary>
  1665. /// Commits editing mode and pushes changes to the backend.
  1666. /// </summary>
  1667. /// <returns>True if operation was successful. False otherwise.</returns>
  1668. public bool CommitEdit()
  1669. {
  1670. return CommitEdit(DataGridEditingUnit.Row, true);
  1671. }
  1672. /// <summary>
  1673. /// Commits editing mode for the specified DataGridEditingUnit and pushes changes to the backend.
  1674. /// </summary>
  1675. /// <param name="editingUnit">Specifies whether to commit edit for a Cell or Row.</param>
  1676. /// <param name="exitEditingMode">Editing mode is left if True.</param>
  1677. /// <returns>True if operation was successful. False otherwise.</returns>
  1678. public bool CommitEdit(DataGridEditingUnit editingUnit, bool exitEditingMode)
  1679. {
  1680. if (!EndCellEdit(
  1681. editAction: DataGridEditAction.Commit,
  1682. exitEditingMode: editingUnit == DataGridEditingUnit.Cell ? exitEditingMode : true,
  1683. keepFocus: ContainsFocus,
  1684. raiseEvents: true))
  1685. {
  1686. return false;
  1687. }
  1688. if (editingUnit == DataGridEditingUnit.Row)
  1689. {
  1690. return EndRowEdit(DataGridEditAction.Commit, exitEditingMode, raiseEvents: true);
  1691. }
  1692. return true;
  1693. }
  1694. /// <summary>
  1695. /// Scrolls the specified item or RowGroupHeader and/or column into view.
  1696. /// If item is not null: scrolls the row representing the item into view;
  1697. /// If column is not null: scrolls the column into view;
  1698. /// If both item and column are null, the method returns without scrolling.
  1699. /// </summary>
  1700. /// <param name="item">an item from the DataGrid's items source or a CollectionViewGroup from the collection view</param>
  1701. /// <param name="column">a column from the DataGrid's columns collection</param>
  1702. public void ScrollIntoView(object item, DataGridColumn column)
  1703. {
  1704. if ((column == null && (item == null || FirstDisplayedNonFillerColumnIndex == -1))
  1705. || (column != null && column.OwningGrid != this))
  1706. {
  1707. // no-op
  1708. return;
  1709. }
  1710. if (item == null)
  1711. {
  1712. // scroll column into view
  1713. ScrollSlotIntoView(
  1714. column.Index,
  1715. DisplayData.FirstScrollingSlot,
  1716. forCurrentCellChange: false,
  1717. forceHorizontalScroll: true);
  1718. }
  1719. else
  1720. {
  1721. int slot = -1;
  1722. DataGridRowGroupInfo rowGroupInfo = null;
  1723. if (item is DataGridCollectionViewGroup collectionViewGroup)
  1724. {
  1725. rowGroupInfo = RowGroupInfoFromCollectionViewGroup(collectionViewGroup);
  1726. if (rowGroupInfo == null)
  1727. {
  1728. Debug.Assert(false);
  1729. return;
  1730. }
  1731. slot = rowGroupInfo.Slot;
  1732. }
  1733. else
  1734. {
  1735. // the row index will be set to -1 if the item is null or not in the list
  1736. int rowIndex = DataConnection.IndexOf(item);
  1737. if (rowIndex == -1)
  1738. {
  1739. return;
  1740. }
  1741. slot = SlotFromRowIndex(rowIndex);
  1742. }
  1743. int columnIndex = (column == null) ? FirstDisplayedNonFillerColumnIndex : column.Index;
  1744. if (_collapsedSlotsTable.Contains(slot))
  1745. {
  1746. // We need to expand all parent RowGroups so that the slot is visible
  1747. if (rowGroupInfo != null)
  1748. {
  1749. ExpandRowGroupParentChain(rowGroupInfo.Level - 1, rowGroupInfo.Slot);
  1750. }
  1751. else
  1752. {
  1753. rowGroupInfo = RowGroupHeadersTable.GetValueAt(RowGroupHeadersTable.GetPreviousIndex(slot));
  1754. Debug.Assert(rowGroupInfo != null);
  1755. if (rowGroupInfo != null)
  1756. {
  1757. ExpandRowGroupParentChain(rowGroupInfo.Level, rowGroupInfo.Slot);
  1758. }
  1759. }
  1760. // Update Scrollbar and display information
  1761. NegVerticalOffset = 0;
  1762. SetVerticalOffset(0);
  1763. ResetDisplayedRows();
  1764. DisplayData.FirstScrollingSlot = 0;
  1765. ComputeScrollBarsLayout();
  1766. }
  1767. ScrollSlotIntoView(
  1768. columnIndex, slot,
  1769. forCurrentCellChange: true,
  1770. forceHorizontalScroll: true);
  1771. }
  1772. }
  1773. /// <summary>
  1774. /// Arranges the content of the <see cref="T:Avalonia.Controls.DataGridRow" />.
  1775. /// </summary>
  1776. /// <param name="finalSize">
  1777. /// The final area within the parent that this element should use to arrange itself and its children.
  1778. /// </param>
  1779. /// <returns>
  1780. /// The actual size used by the <see cref="T:Avalonia.Controls.DataGridRow" />.
  1781. /// </returns>
  1782. protected override Size ArrangeOverride(Size finalSize)
  1783. {
  1784. if (_makeFirstDisplayedCellCurrentCellPending)
  1785. {
  1786. MakeFirstDisplayedCellCurrentCell();
  1787. }
  1788. if (Bounds.Width != finalSize.Width)
  1789. {
  1790. // If our final width has changed, we might need to update the filler
  1791. InvalidateColumnHeadersArrange();
  1792. InvalidateCellsArrange();
  1793. }
  1794. return base.ArrangeOverride(finalSize);
  1795. }
  1796. /// <summary>
  1797. /// Measures the children of a <see cref="T:Avalonia.Controls.DataGridRow" /> to prepare for
  1798. /// arranging them during the
  1799. /// <see cref="M:Avalonia.Controls.DataGridRow.ArrangeOverride(System.Windows.Size)" /> pass.
  1800. /// </summary>
  1801. /// <returns>
  1802. /// The size that the <see cref="T:Avalonia.Controls.DataGridRow" /> determines it needs during layout, based on its calculations of child object allocated sizes.
  1803. /// </returns>
  1804. /// <param name="availableSize">
  1805. /// The available size that this element can give to child elements. Indicates an upper limit that
  1806. /// child elements should not exceed.
  1807. /// </param>
  1808. protected override Size MeasureOverride(Size availableSize)
  1809. {
  1810. // Delay layout until after the initial measure to avoid invalid calculations when the
  1811. // DataGrid is not part of the visual tree
  1812. if (!_measured)
  1813. {
  1814. _measured = true;
  1815. // We don't need to clear the rows because it was already done when the ItemsSource changed
  1816. RefreshRowsAndColumns(clearRows: false);
  1817. //// Update our estimates now that the DataGrid has all of the information necessary
  1818. UpdateRowDetailsHeightEstimate();
  1819. // Update frozen columns to account for columns added prior to loading or autogenerated columns
  1820. if (FrozenColumnCountWithFiller > 0)
  1821. {
  1822. ProcessFrozenColumnCount();
  1823. }
  1824. }
  1825. Size desiredSize;
  1826. // This is a shortcut to skip layout if we don't have any columns
  1827. if (ColumnsInternal.VisibleEdgedColumnsWidth == 0)
  1828. {
  1829. if (_hScrollBar != null && _hScrollBar.IsVisible)
  1830. {
  1831. _hScrollBar.IsVisible = false;
  1832. }
  1833. if (_vScrollBar != null && _vScrollBar.IsVisible)
  1834. {
  1835. _vScrollBar.IsVisible = false;
  1836. }
  1837. desiredSize = base.MeasureOverride(availableSize);
  1838. }
  1839. else
  1840. {
  1841. if (_rowsPresenter != null)
  1842. {
  1843. _rowsPresenter.InvalidateMeasure();
  1844. }
  1845. InvalidateColumnHeadersMeasure();
  1846. desiredSize = base.MeasureOverride(availableSize);
  1847. ComputeScrollBarsLayout();
  1848. }
  1849. return desiredSize;
  1850. }
  1851. /// <summary>
  1852. /// Raises the BeginningEdit event.
  1853. /// </summary>
  1854. protected virtual void OnBeginningEdit(DataGridBeginningEditEventArgs e)
  1855. {
  1856. BeginningEdit?.Invoke(this, e);
  1857. }
  1858. /// <summary>
  1859. /// Raises the CellEditEnded event.
  1860. /// </summary>
  1861. protected virtual void OnCellEditEnded(DataGridCellEditEndedEventArgs e)
  1862. {
  1863. CellEditEnded?.Invoke(this, e);
  1864. }
  1865. /// <summary>
  1866. /// Raises the CellEditEnding event.
  1867. /// </summary>
  1868. protected virtual void OnCellEditEnding(DataGridCellEditEndingEventArgs e)
  1869. {
  1870. CellEditEnding?.Invoke(this, e);
  1871. }
  1872. /// <summary>
  1873. /// Raises the CellPointerPressed event.
  1874. /// </summary>
  1875. internal virtual void OnCellPointerPressed(DataGridCellPointerPressedEventArgs e)
  1876. {
  1877. CellPointerPressed?.Invoke(this, e);
  1878. }
  1879. /// <summary>
  1880. /// Raises the CurrentCellChanged event.
  1881. /// </summary>
  1882. protected virtual void OnCurrentCellChanged(EventArgs e)
  1883. {
  1884. CurrentCellChanged?.Invoke(this, e);
  1885. }
  1886. /// <summary>
  1887. /// Raises the LoadingRow event for row preparation.
  1888. /// </summary>
  1889. protected virtual void OnLoadingRow(DataGridRowEventArgs e)
  1890. {
  1891. EventHandler<DataGridRowEventArgs> handler = LoadingRow;
  1892. if (handler != null)
  1893. {
  1894. Debug.Assert(!_loadedRows.Contains(e.Row));
  1895. _loadedRows.Add(e.Row);
  1896. LoadingOrUnloadingRow = true;
  1897. handler(this, e);
  1898. LoadingOrUnloadingRow = false;
  1899. Debug.Assert(_loadedRows.Contains(e.Row));
  1900. _loadedRows.Remove(e.Row);
  1901. }
  1902. }
  1903. /// <summary>
  1904. /// Scrolls the DataGrid according to the direction of the delta.
  1905. /// </summary>
  1906. /// <param name="e">PointerWheelEventArgs</param>
  1907. protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
  1908. {
  1909. if (IsEnabled && !e.Handled && DisplayData.NumDisplayedScrollingElements > 0)
  1910. {
  1911. double scrollHeight = 0;
  1912. if (e.Delta.Y > 0)
  1913. {
  1914. scrollHeight = Math.Max(-_verticalOffset, -DATAGRID_mouseWheelDelta);
  1915. }
  1916. else if (e.Delta.Y < 0)
  1917. {
  1918. if (_vScrollBar != null && VerticalScrollBarVisibility == ScrollBarVisibility.Visible)
  1919. {
  1920. scrollHeight = Math.Min(Math.Max(0, _vScrollBar.Maximum - _verticalOffset), DATAGRID_mouseWheelDelta);
  1921. }
  1922. else
  1923. {
  1924. double maximum = EdgedRowsHeightCalculated - CellsHeight;
  1925. scrollHeight = Math.Min(Math.Max(0, maximum - _verticalOffset), DATAGRID_mouseWheelDelta);
  1926. }
  1927. }
  1928. if (scrollHeight != 0)
  1929. {
  1930. DisplayData.PendingVerticalScrollHeight = scrollHeight;
  1931. InvalidateRowsMeasure(invalidateIndividualElements: false);
  1932. e.Handled = true;
  1933. }
  1934. }
  1935. }
  1936. /// <summary>
  1937. /// Raises the PreparingCellForEdit event.
  1938. /// </summary>
  1939. protected virtual void OnPreparingCellForEdit(DataGridPreparingCellForEditEventArgs e)
  1940. {
  1941. PreparingCellForEdit?.Invoke(this, e);
  1942. }
  1943. /// <summary>
  1944. /// Raises the RowEditEnded event.
  1945. /// </summary>
  1946. protected virtual void OnRowEditEnded(DataGridRowEditEndedEventArgs e)
  1947. {
  1948. RowEditEnded?.Invoke(this, e);
  1949. }
  1950. /// <summary>
  1951. /// Raises the RowEditEnding event.
  1952. /// </summary>
  1953. protected virtual void OnRowEditEnding(DataGridRowEditEndingEventArgs e)
  1954. {
  1955. RowEditEnding?.Invoke(this, e);
  1956. }
  1957. /// <summary>
  1958. /// Raises the SelectionChanged event and clears the _selectionChanged.
  1959. /// This event won't get raised again until after _selectionChanged is set back to true.
  1960. /// </summary>
  1961. protected virtual void OnSelectionChanged(SelectionChangedEventArgs e)
  1962. {
  1963. RaiseEvent(e);
  1964. }
  1965. /// <summary>
  1966. /// Raises the UnloadingRow event for row recycling.
  1967. /// </summary>
  1968. protected virtual void OnUnloadingRow(DataGridRowEventArgs e)
  1969. {
  1970. EventHandler<DataGridRowEventArgs> handler = UnloadingRow;
  1971. if (handler != null)
  1972. {
  1973. LoadingOrUnloadingRow = true;
  1974. handler(this, e);
  1975. LoadingOrUnloadingRow = false;
  1976. }
  1977. }
  1978. /// <summary>
  1979. /// Builds the visual tree for the column header when a new template is applied.
  1980. /// </summary>
  1981. //TODO Validation UI
  1982. protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
  1983. {
  1984. // The template has changed, so we need to refresh the visuals
  1985. _measured = false;
  1986. if (_columnHeadersPresenter != null)
  1987. {
  1988. // If we're applying a new template, we want to remove the old column headers first
  1989. _columnHeadersPresenter.Children.Clear();
  1990. }
  1991. _columnHeadersPresenter = e.NameScope.Find<DataGridColumnHeadersPresenter>(DATAGRID_elementColumnHeadersPresenterName);
  1992. if (_columnHeadersPresenter != null)
  1993. {
  1994. if (ColumnsInternal.FillerColumn != null)
  1995. {
  1996. ColumnsInternal.FillerColumn.IsRepresented = false;
  1997. }
  1998. _columnHeadersPresenter.OwningGrid = this;
  1999. // Columns were added before before our Template was applied, add the ColumnHeaders now
  2000. foreach (DataGridColumn column in ColumnsItemsInternal)
  2001. {
  2002. InsertDisplayedColumnHeader(column);
  2003. }
  2004. }
  2005. if (_rowsPresenter != null)
  2006. {
  2007. // If we're applying a new template, we want to remove the old rows first
  2008. UnloadElements(recycle: false);
  2009. }
  2010. _rowsPresenter = e.NameScope.Find<DataGridRowsPresenter>(DATAGRID_elementRowsPresenterName);
  2011. if (_rowsPresenter != null)
  2012. {
  2013. _rowsPresenter.OwningGrid = this;
  2014. InvalidateRowHeightEstimate();
  2015. UpdateRowDetailsHeightEstimate();
  2016. }
  2017. _frozenColumnScrollBarSpacer = e.NameScope.Find<Control>(DATAGRID_elementFrozenColumnScrollBarSpacerName);
  2018. if (_hScrollBar != null)
  2019. {
  2020. _hScrollBar.Scroll -= HorizontalScrollBar_Scroll;
  2021. }
  2022. _hScrollBar = e.NameScope.Find<ScrollBar>(DATAGRID_elementHorizontalScrollbarName);
  2023. if (_hScrollBar != null)
  2024. {
  2025. //_hScrollBar.IsTabStop = false;
  2026. _hScrollBar.Maximum = 0.0;
  2027. _hScrollBar.Orientation = Orientation.Horizontal;
  2028. _hScrollBar.IsVisible = false;
  2029. _hScrollBar.Scroll += HorizontalScrollBar_Scroll;
  2030. }
  2031. if (_vScrollBar != null)
  2032. {
  2033. _vScrollBar.Scroll -= VerticalScrollBar_Scroll;
  2034. }
  2035. _vScrollBar = e.NameScope.Find<ScrollBar>(DATAGRID_elementVerticalScrollbarName);
  2036. if (_vScrollBar != null)
  2037. {
  2038. //_vScrollBar.IsTabStop = false;
  2039. _vScrollBar.Maximum = 0.0;
  2040. _vScrollBar.Orientation = Orientation.Vertical;
  2041. _vScrollBar.IsVisible = false;
  2042. _vScrollBar.Scroll += VerticalScrollBar_Scroll;
  2043. }
  2044. _topLeftCornerHeader = e.NameScope.Find<ContentControl>(DATAGRID_elementTopLeftCornerHeaderName);
  2045. EnsureTopLeftCornerHeader(); // EnsureTopLeftCornerHeader checks for a null _topLeftCornerHeader;
  2046. _topRightCornerHeader = e.NameScope.Find<ContentControl>(DATAGRID_elementTopRightCornerHeaderName);
  2047. }
  2048. /// <summary>
  2049. /// Cancels editing mode for the specified DataGridEditingUnit and restores its original value.
  2050. /// </summary>
  2051. /// <param name="editingUnit">Specifies whether to cancel edit for a Cell or Row.</param>
  2052. /// <param name="raiseEvents">Specifies whether or not to raise editing events</param>
  2053. /// <returns>True if operation was successful. False otherwise.</returns>
  2054. internal bool CancelEdit(DataGridEditingUnit editingUnit, bool raiseEvents)
  2055. {
  2056. if (!EndCellEdit(
  2057. DataGridEditAction.Cancel,
  2058. exitEditingMode: true,
  2059. keepFocus: ContainsFocus,
  2060. raiseEvents: raiseEvents))
  2061. {
  2062. return false;
  2063. }
  2064. if (editingUnit == DataGridEditingUnit.Row)
  2065. {
  2066. return EndRowEdit(DataGridEditAction.Cancel, true, raiseEvents);
  2067. }
  2068. return true;
  2069. }
  2070. /// <summary>
  2071. /// call when: selection changes or SelectedItems object changes
  2072. /// </summary>
  2073. internal void CoerceSelectedItem()
  2074. {
  2075. object selectedItem = null;
  2076. if (SelectionMode == DataGridSelectionMode.Extended &&
  2077. CurrentSlot != -1 &&
  2078. _selectedItems.ContainsSlot(CurrentSlot))
  2079. {
  2080. selectedItem = CurrentItem;
  2081. }
  2082. else if (_selectedItems.Count > 0)
  2083. {
  2084. selectedItem = _selectedItems[0];
  2085. }
  2086. SetValueNoCallback(SelectedItemProperty, selectedItem);
  2087. // Update the SelectedIndex
  2088. int newIndex = -1;
  2089. if (selectedItem != null)
  2090. {
  2091. newIndex = DataConnection.IndexOf(selectedItem);
  2092. }
  2093. SetValueNoCallback(SelectedIndexProperty, newIndex);
  2094. }
  2095. internal static DataGridCell GetOwningCell(Control element)
  2096. {
  2097. Debug.Assert(element != null);
  2098. DataGridCell cell = element as DataGridCell;
  2099. while (element != null && cell == null)
  2100. {
  2101. element = element.Parent as Control;
  2102. cell = element as DataGridCell;
  2103. }
  2104. return cell;
  2105. }
  2106. internal IEnumerable<object> GetSelectionInclusive(int startRowIndex, int endRowIndex)
  2107. {
  2108. int endSlot = SlotFromRowIndex(endRowIndex);
  2109. foreach (int slot in _selectedItems.GetSlots(SlotFromRowIndex(startRowIndex)))
  2110. {
  2111. if (slot > endSlot)
  2112. {
  2113. break;
  2114. }
  2115. yield return DataConnection.GetDataItem(RowIndexFromSlot(slot));
  2116. }
  2117. }
  2118. internal void InitializeElements(bool recycleRows)
  2119. {
  2120. try
  2121. {
  2122. _noCurrentCellChangeCount++;
  2123. // The underlying collection has changed and our editing row (if there is one)
  2124. // is no longer relevant, so we should force a cancel edit.
  2125. CancelEdit(DataGridEditingUnit.Row, raiseEvents: false);
  2126. // We want to persist selection throughout a reset, so store away the selected items
  2127. List<object> selectedItemsCache = new List<object>(_selectedItems.SelectedItemsCache);
  2128. if (recycleRows)
  2129. {
  2130. RefreshRows(recycleRows, clearRows: true);
  2131. }
  2132. else
  2133. {
  2134. RefreshRowsAndColumns(clearRows: true);
  2135. }
  2136. // Re-select the old items
  2137. _selectedItems.SelectedItemsCache = selectedItemsCache;
  2138. CoerceSelectedItem();
  2139. if (RowDetailsVisibilityMode != DataGridRowDetailsVisibilityMode.Collapsed)
  2140. {
  2141. UpdateRowDetailsVisibilityMode(RowDetailsVisibilityMode);
  2142. }
  2143. // The currently displayed rows may have incorrect visual states because of the selection change
  2144. ApplyDisplayedRowsState(DisplayData.FirstScrollingSlot, DisplayData.LastScrollingSlot);
  2145. }
  2146. finally
  2147. {
  2148. NoCurrentCellChangeCount--;
  2149. }
  2150. }
  2151. internal bool IsDoubleClickRecordsClickOnCall(Control element)
  2152. {
  2153. if (_clickedElement == element)
  2154. {
  2155. _clickedElement = null;
  2156. return true;
  2157. }
  2158. else
  2159. {
  2160. _clickedElement = element;
  2161. return false;
  2162. }
  2163. }
  2164. // Returns the item or the CollectionViewGroup that is used as the DataContext for a given slot.
  2165. // If the DataContext is an item, rowIndex is set to the index of the item within the collection
  2166. internal object ItemFromSlot(int slot, ref int rowIndex)
  2167. {
  2168. if (RowGroupHeadersTable.Contains(slot))
  2169. {
  2170. return RowGroupHeadersTable.GetValueAt(slot)?.CollectionViewGroup;
  2171. }
  2172. else
  2173. {
  2174. rowIndex = RowIndexFromSlot(slot);
  2175. return DataConnection.GetDataItem(rowIndex);
  2176. }
  2177. }
  2178. internal bool ProcessDownKey(KeyEventArgs e)
  2179. {
  2180. KeyboardHelper.GetMetaKeyState(e.KeyModifiers, out bool ctrl, out bool shift);
  2181. return ProcessDownKeyInternal(shift, ctrl);
  2182. }
  2183. internal bool ProcessEndKey(KeyEventArgs e)
  2184. {
  2185. KeyboardHelper.GetMetaKeyState(e.KeyModifiers, out bool ctrl, out bool shift);
  2186. return ProcessEndKey(shift, ctrl);
  2187. }
  2188. internal bool ProcessEnterKey(KeyEventArgs e)
  2189. {
  2190. KeyboardHelper.GetMetaKeyState(e.KeyModifiers, out bool ctrl, out bool shift);
  2191. return ProcessEnterKey(shift, ctrl);
  2192. }
  2193. internal bool ProcessHomeKey(KeyEventArgs e)
  2194. {
  2195. KeyboardHelper.GetMetaKeyState(e.KeyModifiers, out bool ctrl, out bool shift);
  2196. return ProcessHomeKey(shift, ctrl);
  2197. }
  2198. internal void ProcessHorizontalScroll(ScrollEventType scrollEventType)
  2199. {
  2200. if (_horizontalScrollChangesIgnored > 0)
  2201. {
  2202. return;
  2203. }
  2204. // If the user scrolls with the buttons, we need to update the new value of the scroll bar since we delay
  2205. // this calculation. If they scroll in another other way, the scroll bar's correct value has already been set
  2206. double scrollBarValueDifference = 0;
  2207. if (scrollEventType == ScrollEventType.SmallIncrement)
  2208. {
  2209. scrollBarValueDifference = GetHorizontalSmallScrollIncrease();
  2210. }
  2211. else if (scrollEventType == ScrollEventType.SmallDecrement)
  2212. {
  2213. scrollBarValueDifference = -GetHorizontalSmallScrollDecrease();
  2214. }
  2215. _horizontalScrollChangesIgnored++;
  2216. try
  2217. {
  2218. if (scrollBarValueDifference != 0)
  2219. {
  2220. Debug.Assert(_horizontalOffset + scrollBarValueDifference >= 0);
  2221. _hScrollBar.Value = _horizontalOffset + scrollBarValueDifference;
  2222. }
  2223. UpdateHorizontalOffset(_hScrollBar.Value);
  2224. }
  2225. finally
  2226. {
  2227. _horizontalScrollChangesIgnored--;
  2228. }
  2229. }
  2230. internal bool ProcessLeftKey(KeyEventArgs e)
  2231. {
  2232. KeyboardHelper.GetMetaKeyState(e.KeyModifiers, out bool ctrl, out bool shift);
  2233. return ProcessLeftKey(shift, ctrl);
  2234. }
  2235. internal bool ProcessNextKey(KeyEventArgs e)
  2236. {
  2237. KeyboardHelper.GetMetaKeyState(e.KeyModifiers, out bool ctrl, out bool shift);
  2238. return ProcessNextKey(shift, ctrl);
  2239. }
  2240. internal bool ProcessPriorKey(KeyEventArgs e)
  2241. {
  2242. KeyboardHelper.GetMetaKeyState(e.KeyModifiers, out bool ctrl, out bool shift);
  2243. return ProcessPriorKey(shift, ctrl);
  2244. }
  2245. internal bool ProcessRightKey(KeyEventArgs e)
  2246. {
  2247. KeyboardHelper.GetMetaKeyState(e.KeyModifiers, out bool ctrl, out bool shift);
  2248. return ProcessRightKey(shift, ctrl);
  2249. }
  2250. /// <summary>
  2251. /// Selects items and updates currency based on parameters
  2252. /// </summary>
  2253. /// <param name="columnIndex">column index to make current</param>
  2254. /// <param name="item">data item or CollectionViewGroup to make current</param>
  2255. /// <param name="backupSlot">slot to use in case the item is no longer valid</param>
  2256. /// <param name="action">selection action to perform</param>
  2257. /// <param name="scrollIntoView">whether or not the new current item should be scrolled into view</param>
  2258. internal void ProcessSelectionAndCurrency(int columnIndex, object item, int backupSlot, DataGridSelectionAction action, bool scrollIntoView)
  2259. {
  2260. _noSelectionChangeCount++;
  2261. _noCurrentCellChangeCount++;
  2262. try
  2263. {
  2264. int slot = -1;
  2265. if (item is DataGridCollectionViewGroup group)
  2266. {
  2267. DataGridRowGroupInfo groupInfo = RowGroupInfoFromCollectionViewGroup(group);
  2268. if (groupInfo != null)
  2269. {
  2270. slot = groupInfo.Slot;
  2271. }
  2272. }
  2273. else
  2274. {
  2275. slot = SlotFromRowIndex(DataConnection.IndexOf(item));
  2276. }
  2277. if (slot == -1)
  2278. {
  2279. slot = backupSlot;
  2280. }
  2281. if (slot < 0 || slot > SlotCount)
  2282. {
  2283. return;
  2284. }
  2285. switch (action)
  2286. {
  2287. case DataGridSelectionAction.AddCurrentToSelection:
  2288. SetRowSelection(slot, isSelected: true, setAnchorSlot: true);
  2289. break;
  2290. case DataGridSelectionAction.RemoveCurrentFromSelection:
  2291. SetRowSelection(slot, isSelected: false, setAnchorSlot: false);
  2292. break;
  2293. case DataGridSelectionAction.SelectFromAnchorToCurrent:
  2294. if (SelectionMode == DataGridSelectionMode.Extended && AnchorSlot != -1)
  2295. {
  2296. int anchorSlot = AnchorSlot;
  2297. ClearRowSelection(slot, setAnchorSlot: false);
  2298. if (slot <= anchorSlot)
  2299. {
  2300. SetRowsSelection(slot, anchorSlot);
  2301. }
  2302. else
  2303. {
  2304. SetRowsSelection(anchorSlot, slot);
  2305. }
  2306. }
  2307. else
  2308. {
  2309. goto case DataGridSelectionAction.SelectCurrent;
  2310. }
  2311. break;
  2312. case DataGridSelectionAction.SelectCurrent:
  2313. ClearRowSelection(slot, setAnchorSlot: true);
  2314. break;
  2315. case DataGridSelectionAction.None:
  2316. break;
  2317. }
  2318. if (CurrentSlot != slot || (CurrentColumnIndex != columnIndex && columnIndex != -1))
  2319. {
  2320. if (columnIndex == -1)
  2321. {
  2322. if (CurrentColumnIndex != -1)
  2323. {
  2324. columnIndex = CurrentColumnIndex;
  2325. }
  2326. else
  2327. {
  2328. DataGridColumn firstVisibleColumn = ColumnsInternal.FirstVisibleNonFillerColumn;
  2329. if (firstVisibleColumn != null)
  2330. {
  2331. columnIndex = firstVisibleColumn.Index;
  2332. }
  2333. }
  2334. }
  2335. if (columnIndex != -1)
  2336. {
  2337. if (!SetCurrentCellCore(
  2338. columnIndex, slot,
  2339. commitEdit: true,
  2340. endRowEdit: SlotFromRowIndex(SelectedIndex) != slot)
  2341. || (scrollIntoView &&
  2342. !ScrollSlotIntoView(
  2343. columnIndex, slot,
  2344. forCurrentCellChange: true,
  2345. forceHorizontalScroll: false)))
  2346. {
  2347. return;
  2348. }
  2349. }
  2350. }
  2351. _successfullyUpdatedSelection = true;
  2352. }
  2353. finally
  2354. {
  2355. NoCurrentCellChangeCount--;
  2356. NoSelectionChangeCount--;
  2357. }
  2358. }
  2359. internal bool ProcessUpKey(KeyEventArgs e)
  2360. {
  2361. KeyboardHelper.GetMetaKeyState(e.KeyModifiers, out bool ctrl, out bool shift);
  2362. return ProcessUpKey(shift, ctrl);
  2363. }
  2364. //internal void ProcessVerticalScroll(double oldValue, double newValue)
  2365. internal void ProcessVerticalScroll(ScrollEventType scrollEventType)
  2366. {
  2367. if (_verticalScrollChangesIgnored > 0)
  2368. {
  2369. return;
  2370. }
  2371. Debug.Assert(DoubleUtil.LessThanOrClose(_vScrollBar.Value, _vScrollBar.Maximum));
  2372. _verticalScrollChangesIgnored++;
  2373. try
  2374. {
  2375. Debug.Assert(_vScrollBar != null);
  2376. if (scrollEventType == ScrollEventType.SmallIncrement)
  2377. {
  2378. DisplayData.PendingVerticalScrollHeight = GetVerticalSmallScrollIncrease();
  2379. double newVerticalOffset = _verticalOffset + DisplayData.PendingVerticalScrollHeight;
  2380. if (newVerticalOffset > _vScrollBar.Maximum)
  2381. {
  2382. DisplayData.PendingVerticalScrollHeight -= newVerticalOffset - _vScrollBar.Maximum;
  2383. }
  2384. }
  2385. else if (scrollEventType == ScrollEventType.SmallDecrement)
  2386. {
  2387. if (DoubleUtil.GreaterThan(NegVerticalOffset, 0))
  2388. {
  2389. DisplayData.PendingVerticalScrollHeight -= NegVerticalOffset;
  2390. }
  2391. else
  2392. {
  2393. int previousScrollingSlot = GetPreviousVisibleSlot(DisplayData.FirstScrollingSlot);
  2394. if (previousScrollingSlot >= 0)
  2395. {
  2396. ScrollSlotIntoView(previousScrollingSlot, scrolledHorizontally: false);
  2397. }
  2398. return;
  2399. }
  2400. }
  2401. else
  2402. {
  2403. DisplayData.PendingVerticalScrollHeight = _vScrollBar.Value - _verticalOffset;
  2404. }
  2405. if (!DoubleUtil.IsZero(DisplayData.PendingVerticalScrollHeight))
  2406. {
  2407. // Invalidate so the scroll happens on idle
  2408. InvalidateRowsMeasure(invalidateIndividualElements: false);
  2409. }
  2410. }
  2411. finally
  2412. {
  2413. _verticalScrollChangesIgnored--;
  2414. }
  2415. }
  2416. internal void RefreshRowsAndColumns(bool clearRows)
  2417. {
  2418. if (_measured)
  2419. {
  2420. try
  2421. {
  2422. _noCurrentCellChangeCount++;
  2423. if (clearRows)
  2424. {
  2425. ClearRows(false);
  2426. ClearRowGroupHeadersTable();
  2427. PopulateRowGroupHeadersTable();
  2428. }
  2429. if (AutoGenerateColumns)
  2430. {
  2431. //Column auto-generation refreshes the rows too
  2432. AutoGenerateColumnsPrivate();
  2433. }
  2434. foreach (DataGridColumn column in ColumnsItemsInternal)
  2435. {
  2436. //We don't need to refresh the state of AutoGenerated column headers because they're up-to-date
  2437. if (!column.IsAutoGenerated && column.HasHeaderCell)
  2438. {
  2439. column.HeaderCell.ApplyState();
  2440. }
  2441. }
  2442. RefreshRows(recycleRows: false, clearRows: false);
  2443. if (Columns.Count > 0 && CurrentColumnIndex == -1)
  2444. {
  2445. MakeFirstDisplayedCellCurrentCell();
  2446. }
  2447. else
  2448. {
  2449. _makeFirstDisplayedCellCurrentCellPending = false;
  2450. _desiredCurrentColumnIndex = -1;
  2451. FlushCurrentCellChanged();
  2452. }
  2453. }
  2454. finally
  2455. {
  2456. NoCurrentCellChangeCount--;
  2457. }
  2458. }
  2459. else
  2460. {
  2461. if (clearRows)
  2462. {
  2463. ClearRows(recycle: false);
  2464. }
  2465. ClearRowGroupHeadersTable();
  2466. PopulateRowGroupHeadersTable();
  2467. }
  2468. }
  2469. internal bool ScrollSlotIntoView(int columnIndex, int slot, bool forCurrentCellChange, bool forceHorizontalScroll)
  2470. {
  2471. Debug.Assert(columnIndex >= 0 && columnIndex < ColumnsItemsInternal.Count);
  2472. Debug.Assert(DisplayData.FirstDisplayedScrollingCol >= -1 && DisplayData.FirstDisplayedScrollingCol < ColumnsItemsInternal.Count);
  2473. Debug.Assert(DisplayData.LastTotallyDisplayedScrollingCol >= -1 && DisplayData.LastTotallyDisplayedScrollingCol < ColumnsItemsInternal.Count);
  2474. Debug.Assert(!IsSlotOutOfBounds(slot));
  2475. Debug.Assert(DisplayData.FirstScrollingSlot >= -1 && DisplayData.FirstScrollingSlot < SlotCount);
  2476. Debug.Assert(ColumnsItemsInternal[columnIndex].IsVisible);
  2477. if (CurrentColumnIndex >= 0 &&
  2478. (CurrentColumnIndex != columnIndex || CurrentSlot != slot))
  2479. {
  2480. if (!CommitEditForOperation(columnIndex, slot, forCurrentCellChange) || IsInnerCellOutOfBounds(columnIndex, slot))
  2481. {
  2482. return false;
  2483. }
  2484. }
  2485. double oldHorizontalOffset = HorizontalOffset;
  2486. //scroll horizontally unless we're on a RowGroupHeader and we're not forcing horizontal scrolling
  2487. if ((forceHorizontalScroll || (slot != -1))
  2488. && !ScrollColumnIntoView(columnIndex))
  2489. {
  2490. return false;
  2491. }
  2492. //scroll vertically
  2493. if (!ScrollSlotIntoView(slot, scrolledHorizontally: oldHorizontalOffset != HorizontalOffset))
  2494. {
  2495. return false;
  2496. }
  2497. return true;
  2498. }
  2499. // Convenient overload that commits the current edit.
  2500. internal bool SetCurrentCellCore(int columnIndex, int slot)
  2501. {
  2502. return SetCurrentCellCore(columnIndex, slot, commitEdit: true, endRowEdit: true);
  2503. }
  2504. internal void UpdateHorizontalOffset(double newValue)
  2505. {
  2506. if (HorizontalOffset != newValue)
  2507. {
  2508. HorizontalOffset = newValue;
  2509. InvalidateColumnHeadersMeasure();
  2510. InvalidateRowsMeasure(true);
  2511. }
  2512. }
  2513. internal bool UpdateSelectionAndCurrency(int columnIndex, int slot, DataGridSelectionAction action, bool scrollIntoView)
  2514. {
  2515. _successfullyUpdatedSelection = false;
  2516. _noSelectionChangeCount++;
  2517. _noCurrentCellChangeCount++;
  2518. try
  2519. {
  2520. if (ColumnsInternal.RowGroupSpacerColumn.IsRepresented &&
  2521. columnIndex == ColumnsInternal.RowGroupSpacerColumn.Index)
  2522. {
  2523. columnIndex = -1;
  2524. }
  2525. if (IsSlotOutOfSelectionBounds(slot) || (columnIndex != -1 && IsColumnOutOfBounds(columnIndex)))
  2526. {
  2527. return false;
  2528. }
  2529. int newCurrentPosition = -1;
  2530. object item = ItemFromSlot(slot, ref newCurrentPosition);
  2531. if (EditingRow != null && slot != EditingRow.Slot && !CommitEdit(DataGridEditingUnit.Row, true))
  2532. {
  2533. return false;
  2534. }
  2535. if (DataConnection.CollectionView != null &&
  2536. DataConnection.CollectionView.CurrentPosition != newCurrentPosition)
  2537. {
  2538. DataConnection.MoveCurrentTo(item, slot, columnIndex, action, scrollIntoView);
  2539. }
  2540. else
  2541. {
  2542. ProcessSelectionAndCurrency(columnIndex, item, slot, action, scrollIntoView);
  2543. }
  2544. }
  2545. finally
  2546. {
  2547. NoCurrentCellChangeCount--;
  2548. NoSelectionChangeCount--;
  2549. }
  2550. return _successfullyUpdatedSelection;
  2551. }
  2552. internal void UpdateStateOnCurrentChanged(object currentItem, int currentPosition)
  2553. {
  2554. if (currentItem == CurrentItem && currentItem == SelectedItem && currentPosition == SelectedIndex)
  2555. {
  2556. // The DataGrid's CurrentItem is already up-to-date, so we don't need to do anything
  2557. return;
  2558. }
  2559. int columnIndex = CurrentColumnIndex;
  2560. if (columnIndex == -1)
  2561. {
  2562. if (IsColumnOutOfBounds(_desiredCurrentColumnIndex) ||
  2563. (ColumnsInternal.RowGroupSpacerColumn.IsRepresented && _desiredCurrentColumnIndex == ColumnsInternal.RowGroupSpacerColumn.Index))
  2564. {
  2565. columnIndex = FirstDisplayedNonFillerColumnIndex;
  2566. }
  2567. else
  2568. {
  2569. columnIndex = _desiredCurrentColumnIndex;
  2570. }
  2571. }
  2572. _desiredCurrentColumnIndex = -1;
  2573. try
  2574. {
  2575. _noSelectionChangeCount++;
  2576. _noCurrentCellChangeCount++;
  2577. if (!CommitEdit())
  2578. {
  2579. CancelEdit(DataGridEditingUnit.Row, false);
  2580. }
  2581. ClearRowSelection(true);
  2582. if (currentItem == null)
  2583. {
  2584. SetCurrentCellCore(-1, -1);
  2585. }
  2586. else
  2587. {
  2588. int slot = SlotFromRowIndex(currentPosition);
  2589. ProcessSelectionAndCurrency(columnIndex, currentItem, slot, DataGridSelectionAction.SelectCurrent, false);
  2590. }
  2591. }
  2592. finally
  2593. {
  2594. NoCurrentCellChangeCount--;
  2595. NoSelectionChangeCount--;
  2596. }
  2597. }
  2598. //TODO: Ensure left button is checked for
  2599. internal bool UpdateStateOnMouseLeftButtonDown(PointerPressedEventArgs pointerPressedEventArgs, int columnIndex, int slot, bool allowEdit)
  2600. {
  2601. KeyboardHelper.GetMetaKeyState(pointerPressedEventArgs.KeyModifiers, out bool ctrl, out bool shift);
  2602. return UpdateStateOnMouseLeftButtonDown(pointerPressedEventArgs, columnIndex, slot, allowEdit, shift, ctrl);
  2603. }
  2604. internal void UpdateVerticalScrollBar()
  2605. {
  2606. if (_vScrollBar != null && _vScrollBar.IsVisible)
  2607. {
  2608. double cellsHeight = CellsHeight;
  2609. double edgedRowsHeightCalculated = EdgedRowsHeightCalculated;
  2610. UpdateVerticalScrollBar(
  2611. needVertScrollbar: edgedRowsHeightCalculated > cellsHeight,
  2612. forceVertScrollbar: VerticalScrollBarVisibility == ScrollBarVisibility.Visible,
  2613. totalVisibleHeight: edgedRowsHeightCalculated,
  2614. cellsHeight: cellsHeight);
  2615. }
  2616. }
  2617. /// <summary>
  2618. /// If the editing element has focus, this method will set focus to the DataGrid itself
  2619. /// in order to force the element to lose focus. It will then wait for the editing element's
  2620. /// LostFocus event, at which point it will perform the specified action.
  2621. ///
  2622. /// NOTE: It is important to understand that the specified action will be performed when the editing
  2623. /// element loses focus only if this method returns true. If it returns false, then the action
  2624. /// will not be performed later on, and should instead be performed by the caller, if necessary.
  2625. /// </summary>
  2626. /// <param name="action">Action to perform after the editing element loses focus</param>
  2627. /// <returns>True if the editing element had focus and the action was cached away; false otherwise</returns>
  2628. //TODO TabStop
  2629. internal bool WaitForLostFocus(Action action)
  2630. {
  2631. if (EditingRow != null && EditingColumnIndex != -1 && !_executingLostFocusActions)
  2632. {
  2633. DataGridColumn editingColumn = ColumnsItemsInternal[EditingColumnIndex];
  2634. IControl editingElement = editingColumn.GetCellContent(EditingRow);
  2635. if (editingElement != null && editingElement.ContainsChild(_focusedObject))
  2636. {
  2637. Debug.Assert(_lostFocusActions != null);
  2638. _lostFocusActions.Enqueue(action);
  2639. editingElement.LostFocus += EditingElement_LostFocus;
  2640. //IsTabStop = true;
  2641. Focus();
  2642. return true;
  2643. }
  2644. }
  2645. return false;
  2646. }
  2647. /// <summary>
  2648. /// Raises the LoadingRowDetails for row details preparation
  2649. /// </summary>
  2650. protected virtual void OnLoadingRowDetails(DataGridRowDetailsEventArgs e)
  2651. {
  2652. EventHandler<DataGridRowDetailsEventArgs> handler = LoadingRowDetails;
  2653. if (handler != null)
  2654. {
  2655. LoadingOrUnloadingRow = true;
  2656. handler(this, e);
  2657. LoadingOrUnloadingRow = false;
  2658. }
  2659. }
  2660. /// <summary>
  2661. /// Raises the UnloadingRowDetails event
  2662. /// </summary>
  2663. protected virtual void OnUnloadingRowDetails(DataGridRowDetailsEventArgs e)
  2664. {
  2665. EventHandler<DataGridRowDetailsEventArgs> handler = UnloadingRowDetails;
  2666. if (handler != null)
  2667. {
  2668. LoadingOrUnloadingRow = true;
  2669. handler(this, e);
  2670. LoadingOrUnloadingRow = false;
  2671. }
  2672. }
  2673. internal void OnRowDetailsChanged()
  2674. {
  2675. if (!_scrollingByHeight)
  2676. {
  2677. // Update layout when RowDetails are expanded or collapsed, just updating the vertical scroll bar is not enough
  2678. // since rows could be added or removed
  2679. InvalidateMeasure();
  2680. }
  2681. }
  2682. private void UpdateRowDetailsVisibilityMode(DataGridRowDetailsVisibilityMode newDetailsMode)
  2683. {
  2684. int itemCount = DataConnection.Count;
  2685. if (_rowsPresenter != null && itemCount > 0)
  2686. {
  2687. bool newDetailsVisibility = false;
  2688. switch (newDetailsMode)
  2689. {
  2690. case DataGridRowDetailsVisibilityMode.Visible:
  2691. newDetailsVisibility = true;
  2692. _showDetailsTable.AddValues(0, itemCount, true);
  2693. break;
  2694. case DataGridRowDetailsVisibilityMode.Collapsed:
  2695. newDetailsVisibility = false;
  2696. _showDetailsTable.AddValues(0, itemCount, false);
  2697. break;
  2698. case DataGridRowDetailsVisibilityMode.VisibleWhenSelected:
  2699. _showDetailsTable.Clear();
  2700. break;
  2701. }
  2702. bool updated = false;
  2703. foreach (DataGridRow row in GetAllRows())
  2704. {
  2705. if (row.IsVisible)
  2706. {
  2707. if (newDetailsMode == DataGridRowDetailsVisibilityMode.VisibleWhenSelected)
  2708. {
  2709. // For VisibleWhenSelected, we need to calculate the value for each individual row
  2710. newDetailsVisibility = _selectedItems.ContainsSlot(row.Slot);
  2711. }
  2712. if (row.AreDetailsVisible != newDetailsVisibility)
  2713. {
  2714. updated = true;
  2715. row.SetDetailsVisibilityInternal(newDetailsVisibility, raiseNotification: true, animate: false);
  2716. }
  2717. }
  2718. }
  2719. if (updated)
  2720. {
  2721. UpdateDisplayedRows(DisplayData.FirstScrollingSlot, CellsHeight);
  2722. InvalidateRowsMeasure(invalidateIndividualElements: false);
  2723. }
  2724. }
  2725. }
  2726. //TODO Styles
  2727. private void AddNewCellPrivate(DataGridRow row, DataGridColumn column)
  2728. {
  2729. DataGridCell newCell = new DataGridCell();
  2730. PopulateCellContent(
  2731. isCellEdited: false,
  2732. dataGridColumn: column,
  2733. dataGridRow: row,
  2734. dataGridCell: newCell);
  2735. if (row.OwningGrid != null)
  2736. {
  2737. newCell.OwningColumn = column;
  2738. newCell.IsVisible = column.IsVisible;
  2739. }
  2740. //newCell.EnsureStyle(null);
  2741. row.Cells.Insert(column.Index, newCell);
  2742. }
  2743. private bool BeginCellEdit(RoutedEventArgs editingEventArgs)
  2744. {
  2745. if (CurrentColumnIndex == -1 || !GetRowSelection(CurrentSlot))
  2746. {
  2747. return false;
  2748. }
  2749. Debug.Assert(CurrentColumnIndex >= 0);
  2750. Debug.Assert(CurrentColumnIndex < ColumnsItemsInternal.Count);
  2751. Debug.Assert(CurrentSlot >= -1);
  2752. Debug.Assert(CurrentSlot < SlotCount);
  2753. Debug.Assert(EditingRow == null || EditingRow.Slot == CurrentSlot);
  2754. Debug.Assert(!GetColumnEffectiveReadOnlyState(CurrentColumn));
  2755. Debug.Assert(CurrentColumn.IsVisible);
  2756. if (_editingColumnIndex != -1)
  2757. {
  2758. // Current cell is already in edit mode
  2759. Debug.Assert(_editingColumnIndex == CurrentColumnIndex);
  2760. return true;
  2761. }
  2762. // Get or generate the editing row if it doesn't exist
  2763. DataGridRow dataGridRow = EditingRow;
  2764. if (dataGridRow == null)
  2765. {
  2766. if (IsSlotVisible(CurrentSlot))
  2767. {
  2768. dataGridRow = DisplayData.GetDisplayedElement(CurrentSlot) as DataGridRow;
  2769. Debug.Assert(dataGridRow != null);
  2770. }
  2771. else
  2772. {
  2773. dataGridRow = GenerateRow(RowIndexFromSlot(CurrentSlot), CurrentSlot);
  2774. }
  2775. }
  2776. Debug.Assert(dataGridRow != null);
  2777. // Cache these to see if they change later
  2778. int currentRowIndex = CurrentSlot;
  2779. int currentColumnIndex = CurrentColumnIndex;
  2780. // Raise the BeginningEdit event
  2781. DataGridCell dataGridCell = dataGridRow.Cells[CurrentColumnIndex];
  2782. DataGridBeginningEditEventArgs e = new DataGridBeginningEditEventArgs(CurrentColumn, dataGridRow, editingEventArgs);
  2783. OnBeginningEdit(e);
  2784. if (e.Cancel
  2785. || currentRowIndex != CurrentSlot
  2786. || currentColumnIndex != CurrentColumnIndex
  2787. || !GetRowSelection(CurrentSlot)
  2788. || (EditingRow == null && !BeginRowEdit(dataGridRow)))
  2789. {
  2790. // If either BeginningEdit was canceled, currency/selection was changed in the event handler,
  2791. // or we failed opening the row for edit, then we can no longer continue BeginCellEdit
  2792. return false;
  2793. }
  2794. Debug.Assert(EditingRow != null);
  2795. Debug.Assert(EditingRow.Slot == CurrentSlot);
  2796. // Finally, we can prepare the cell for editing
  2797. _editingColumnIndex = CurrentColumnIndex;
  2798. _editingEventArgs = editingEventArgs;
  2799. EditingRow.Cells[CurrentColumnIndex].UpdatePseudoClasses();
  2800. PopulateCellContent(
  2801. isCellEdited: true,
  2802. dataGridColumn: CurrentColumn,
  2803. dataGridRow: dataGridRow,
  2804. dataGridCell: dataGridCell);
  2805. return true;
  2806. }
  2807. //TODO Validation
  2808. private bool BeginRowEdit(DataGridRow dataGridRow)
  2809. {
  2810. Debug.Assert(EditingRow == null);
  2811. Debug.Assert(dataGridRow != null);
  2812. Debug.Assert(CurrentSlot >= -1);
  2813. Debug.Assert(CurrentSlot < SlotCount);
  2814. if (DataConnection.BeginEdit(dataGridRow.DataContext))
  2815. {
  2816. EditingRow = dataGridRow;
  2817. GenerateEditingElements();
  2818. return true;
  2819. }
  2820. return false;
  2821. }
  2822. private bool CancelRowEdit(bool exitEditingMode)
  2823. {
  2824. if (EditingRow == null)
  2825. {
  2826. return true;
  2827. }
  2828. Debug.Assert(EditingRow != null && EditingRow.Index >= -1);
  2829. Debug.Assert(EditingRow.Slot < SlotCount);
  2830. Debug.Assert(CurrentColumn != null);
  2831. object dataItem = EditingRow.DataContext;
  2832. if (!DataConnection.CancelEdit(dataItem))
  2833. {
  2834. return false;
  2835. }
  2836. foreach (DataGridColumn column in Columns)
  2837. {
  2838. if (!exitEditingMode && column.Index == _editingColumnIndex && column is DataGridBoundColumn)
  2839. {
  2840. continue;
  2841. }
  2842. PopulateCellContent(
  2843. isCellEdited: !exitEditingMode && column.Index == _editingColumnIndex,
  2844. dataGridColumn: column,
  2845. dataGridRow: EditingRow,
  2846. dataGridCell: EditingRow.Cells[column.Index]);
  2847. }
  2848. return true;
  2849. }
  2850. private bool CommitEditForOperation(int columnIndex, int slot, bool forCurrentCellChange)
  2851. {
  2852. if (forCurrentCellChange)
  2853. {
  2854. if (!EndCellEdit(DataGridEditAction.Commit, exitEditingMode: true, keepFocus: true, raiseEvents: true))
  2855. {
  2856. return false;
  2857. }
  2858. if (CurrentSlot != slot &&
  2859. !EndRowEdit(DataGridEditAction.Commit, exitEditingMode: true, raiseEvents: true))
  2860. {
  2861. return false;
  2862. }
  2863. }
  2864. if (IsColumnOutOfBounds(columnIndex))
  2865. {
  2866. return false;
  2867. }
  2868. if (slot >= SlotCount)
  2869. {
  2870. // Current cell was reset because the commit deleted row(s).
  2871. // Since the user wants to change the current cell, we don't
  2872. // want to end up with no current cell. We pick the last row
  2873. // in the grid which may be the 'new row'.
  2874. int lastSlot = LastVisibleSlot;
  2875. if (forCurrentCellChange &&
  2876. CurrentColumnIndex == -1 &&
  2877. lastSlot != -1)
  2878. {
  2879. SetAndSelectCurrentCell(columnIndex, lastSlot, forceCurrentCellSelection: false);
  2880. }
  2881. // Interrupt operation because it has become invalid.
  2882. return false;
  2883. }
  2884. return true;
  2885. }
  2886. //TODO Validation
  2887. private bool CommitRowEdit(bool exitEditingMode)
  2888. {
  2889. if (EditingRow == null)
  2890. {
  2891. return true;
  2892. }
  2893. Debug.Assert(EditingRow != null && EditingRow.Index >= -1);
  2894. Debug.Assert(EditingRow.Slot < SlotCount);
  2895. //if (!ValidateEditingRow(scrollIntoView: true, wireEvents: false))
  2896. if (!EditingRow.IsValid)
  2897. {
  2898. return false;
  2899. }
  2900. DataConnection.EndEdit(EditingRow.DataContext);
  2901. if (!exitEditingMode)
  2902. {
  2903. DataConnection.BeginEdit(EditingRow.DataContext);
  2904. }
  2905. return true;
  2906. }
  2907. private void CompleteCellsCollection(DataGridRow dataGridRow)
  2908. {
  2909. Debug.Assert(dataGridRow != null);
  2910. int cellsInCollection = dataGridRow.Cells.Count;
  2911. if (ColumnsItemsInternal.Count > cellsInCollection)
  2912. {
  2913. for (int columnIndex = cellsInCollection; columnIndex < ColumnsItemsInternal.Count; columnIndex++)
  2914. {
  2915. AddNewCellPrivate(dataGridRow, ColumnsItemsInternal[columnIndex]);
  2916. }
  2917. }
  2918. }
  2919. private void ComputeScrollBarsLayout()
  2920. {
  2921. if (_ignoreNextScrollBarsLayout)
  2922. {
  2923. _ignoreNextScrollBarsLayout = false;
  2924. //
  2925. }
  2926. double cellsWidth = CellsWidth;
  2927. double cellsHeight = CellsHeight;
  2928. bool allowHorizScrollbar = false;
  2929. bool forceHorizScrollbar = false;
  2930. double horizScrollBarHeight = 0;
  2931. if (_hScrollBar != null)
  2932. {
  2933. forceHorizScrollbar = HorizontalScrollBarVisibility == ScrollBarVisibility.Visible;
  2934. allowHorizScrollbar = forceHorizScrollbar || (ColumnsInternal.VisibleColumnCount > 0 &&
  2935. HorizontalScrollBarVisibility != ScrollBarVisibility.Disabled &&
  2936. HorizontalScrollBarVisibility != ScrollBarVisibility.Hidden);
  2937. // Compensate if the horizontal scrollbar is already taking up space
  2938. if (!forceHorizScrollbar && _hScrollBar.IsVisible)
  2939. {
  2940. cellsHeight += _hScrollBar.DesiredSize.Height;
  2941. }
  2942. horizScrollBarHeight = _hScrollBar.Height + _hScrollBar.Margin.Top + _hScrollBar.Margin.Bottom;
  2943. }
  2944. bool allowVertScrollbar = false;
  2945. bool forceVertScrollbar = false;
  2946. double vertScrollBarWidth = 0;
  2947. if (_vScrollBar != null)
  2948. {
  2949. forceVertScrollbar = VerticalScrollBarVisibility == ScrollBarVisibility.Visible;
  2950. allowVertScrollbar = forceVertScrollbar || (ColumnsItemsInternal.Count > 0 &&
  2951. VerticalScrollBarVisibility != ScrollBarVisibility.Disabled &&
  2952. VerticalScrollBarVisibility != ScrollBarVisibility.Hidden);
  2953. // Compensate if the vertical scrollbar is already taking up space
  2954. if (!forceVertScrollbar && _vScrollBar.IsVisible)
  2955. {
  2956. cellsWidth += _vScrollBar.DesiredSize.Width;
  2957. }
  2958. vertScrollBarWidth = _vScrollBar.Width + _vScrollBar.Margin.Left + _vScrollBar.Margin.Right;
  2959. }
  2960. // Now cellsWidth is the width potentially available for displaying data cells.
  2961. // Now cellsHeight is the height potentially available for displaying data cells.
  2962. bool needHorizScrollbar = false;
  2963. bool needVertScrollbar = false;
  2964. double totalVisibleWidth = ColumnsInternal.VisibleEdgedColumnsWidth;
  2965. double totalVisibleFrozenWidth = ColumnsInternal.GetVisibleFrozenEdgedColumnsWidth();
  2966. UpdateDisplayedRows(DisplayData.FirstScrollingSlot, CellsHeight);
  2967. double totalVisibleHeight = EdgedRowsHeightCalculated;
  2968. if (!forceHorizScrollbar && !forceVertScrollbar)
  2969. {
  2970. bool needHorizScrollbarWithoutVertScrollbar = false;
  2971. if (allowHorizScrollbar &&
  2972. DoubleUtil.GreaterThan(totalVisibleWidth, cellsWidth) &&
  2973. DoubleUtil.LessThan(totalVisibleFrozenWidth, cellsWidth) &&
  2974. DoubleUtil.LessThanOrClose(horizScrollBarHeight, cellsHeight))
  2975. {
  2976. double oldDataHeight = cellsHeight;
  2977. cellsHeight -= horizScrollBarHeight;
  2978. Debug.Assert(cellsHeight >= 0);
  2979. needHorizScrollbarWithoutVertScrollbar = needHorizScrollbar = true;
  2980. if (allowVertScrollbar && (DoubleUtil.LessThanOrClose(totalVisibleWidth - cellsWidth, vertScrollBarWidth) ||
  2981. DoubleUtil.LessThanOrClose(cellsWidth - totalVisibleFrozenWidth, vertScrollBarWidth)))
  2982. {
  2983. // Would we still need a horizontal scrollbar without the vertical one?
  2984. UpdateDisplayedRows(DisplayData.FirstScrollingSlot, cellsHeight);
  2985. if (DisplayData.NumTotallyDisplayedScrollingElements != VisibleSlotCount)
  2986. {
  2987. needHorizScrollbar = DoubleUtil.LessThan(totalVisibleFrozenWidth, cellsWidth - vertScrollBarWidth);
  2988. }
  2989. }
  2990. if (!needHorizScrollbar)
  2991. {
  2992. // Restore old data height because turns out a horizontal scroll bar wouldn't make sense
  2993. cellsHeight = oldDataHeight;
  2994. }
  2995. }
  2996. UpdateDisplayedRows(DisplayData.FirstScrollingSlot, cellsHeight);
  2997. if (allowVertScrollbar &&
  2998. DoubleUtil.GreaterThan(cellsHeight, 0) &&
  2999. DoubleUtil.LessThanOrClose(vertScrollBarWidth, cellsWidth) &&
  3000. DisplayData.NumTotallyDisplayedScrollingElements != VisibleSlotCount)
  3001. {
  3002. cellsWidth -= vertScrollBarWidth;
  3003. Debug.Assert(cellsWidth >= 0);
  3004. needVertScrollbar = true;
  3005. }
  3006. DisplayData.FirstDisplayedScrollingCol = ComputeFirstVisibleScrollingColumn();
  3007. // we compute the number of visible columns only after we set up the vertical scroll bar.
  3008. ComputeDisplayedColumns();
  3009. if (allowHorizScrollbar &&
  3010. needVertScrollbar && !needHorizScrollbar &&
  3011. DoubleUtil.GreaterThan(totalVisibleWidth, cellsWidth) &&
  3012. DoubleUtil.LessThan(totalVisibleFrozenWidth, cellsWidth) &&
  3013. DoubleUtil.LessThanOrClose(horizScrollBarHeight, cellsHeight))
  3014. {
  3015. cellsWidth += vertScrollBarWidth;
  3016. cellsHeight -= horizScrollBarHeight;
  3017. Debug.Assert(cellsHeight >= 0);
  3018. needVertScrollbar = false;
  3019. UpdateDisplayedRows(DisplayData.FirstScrollingSlot, cellsHeight);
  3020. if (cellsHeight > 0 &&
  3021. vertScrollBarWidth <= cellsWidth &&
  3022. DisplayData.NumTotallyDisplayedScrollingElements != VisibleSlotCount)
  3023. {
  3024. cellsWidth -= vertScrollBarWidth;
  3025. Debug.Assert(cellsWidth >= 0);
  3026. needVertScrollbar = true;
  3027. }
  3028. if (needVertScrollbar)
  3029. {
  3030. needHorizScrollbar = true;
  3031. }
  3032. else
  3033. {
  3034. needHorizScrollbar = needHorizScrollbarWithoutVertScrollbar;
  3035. }
  3036. }
  3037. }
  3038. else if (forceHorizScrollbar && !forceVertScrollbar)
  3039. {
  3040. if (allowVertScrollbar)
  3041. {
  3042. if (cellsHeight > 0 &&
  3043. DoubleUtil.LessThanOrClose(vertScrollBarWidth, cellsWidth) &&
  3044. DisplayData.NumTotallyDisplayedScrollingElements != VisibleSlotCount)
  3045. {
  3046. cellsWidth -= vertScrollBarWidth;
  3047. Debug.Assert(cellsWidth >= 0);
  3048. needVertScrollbar = true;
  3049. }
  3050. DisplayData.FirstDisplayedScrollingCol = ComputeFirstVisibleScrollingColumn();
  3051. ComputeDisplayedColumns();
  3052. }
  3053. needHorizScrollbar = totalVisibleWidth > cellsWidth && totalVisibleFrozenWidth < cellsWidth;
  3054. }
  3055. else if (!forceHorizScrollbar && forceVertScrollbar)
  3056. {
  3057. if (allowHorizScrollbar)
  3058. {
  3059. if (cellsWidth > 0 &&
  3060. DoubleUtil.LessThanOrClose(horizScrollBarHeight, cellsHeight) &&
  3061. DoubleUtil.GreaterThan(totalVisibleWidth, cellsWidth) &&
  3062. DoubleUtil.LessThan(totalVisibleFrozenWidth, cellsWidth))
  3063. {
  3064. cellsHeight -= horizScrollBarHeight;
  3065. Debug.Assert(cellsHeight >= 0);
  3066. needHorizScrollbar = true;
  3067. UpdateDisplayedRows(DisplayData.FirstScrollingSlot, cellsHeight);
  3068. }
  3069. DisplayData.FirstDisplayedScrollingCol = ComputeFirstVisibleScrollingColumn();
  3070. ComputeDisplayedColumns();
  3071. }
  3072. needVertScrollbar = DisplayData.NumTotallyDisplayedScrollingElements != VisibleSlotCount;
  3073. }
  3074. else
  3075. {
  3076. Debug.Assert(forceHorizScrollbar && forceVertScrollbar);
  3077. Debug.Assert(allowHorizScrollbar && allowVertScrollbar);
  3078. DisplayData.FirstDisplayedScrollingCol = ComputeFirstVisibleScrollingColumn();
  3079. ComputeDisplayedColumns();
  3080. needVertScrollbar = DisplayData.NumTotallyDisplayedScrollingElements != VisibleSlotCount;
  3081. needHorizScrollbar = totalVisibleWidth > cellsWidth && totalVisibleFrozenWidth < cellsWidth;
  3082. }
  3083. UpdateHorizontalScrollBar(needHorizScrollbar, forceHorizScrollbar, totalVisibleWidth, totalVisibleFrozenWidth, cellsWidth);
  3084. UpdateVerticalScrollBar(needVertScrollbar, forceVertScrollbar, totalVisibleHeight, cellsHeight);
  3085. if (_topRightCornerHeader != null)
  3086. {
  3087. // Show the TopRightHeaderCell based on vertical ScrollBar visibility
  3088. if (AreColumnHeadersVisible &&
  3089. _vScrollBar != null && _vScrollBar.IsVisible)
  3090. {
  3091. _topRightCornerHeader.IsVisible = true;
  3092. }
  3093. else
  3094. {
  3095. _topRightCornerHeader.IsVisible = false;
  3096. }
  3097. }
  3098. DisplayData.FullyRecycleElements();
  3099. }
  3100. /// <summary>
  3101. /// Handles the current editing element's LostFocus event by performing any actions that
  3102. /// were cached by the WaitForLostFocus method.
  3103. /// </summary>
  3104. /// <param name="sender">Editing element</param>
  3105. /// <param name="e">RoutedEventArgs</param>
  3106. private void EditingElement_LostFocus(object sender, RoutedEventArgs e)
  3107. {
  3108. if (sender is Control editingElement)
  3109. {
  3110. editingElement.LostFocus -= EditingElement_LostFocus;
  3111. if (EditingRow != null && EditingColumnIndex != -1)
  3112. {
  3113. FocusEditingCell(true);
  3114. }
  3115. Debug.Assert(_lostFocusActions != null);
  3116. try
  3117. {
  3118. _executingLostFocusActions = true;
  3119. while (_lostFocusActions.Count > 0)
  3120. {
  3121. _lostFocusActions.Dequeue()();
  3122. }
  3123. }
  3124. finally
  3125. {
  3126. _executingLostFocusActions = false;
  3127. }
  3128. }
  3129. }
  3130. // Makes sure horizontal layout is updated to reflect any changes that affect it
  3131. private void EnsureHorizontalLayout()
  3132. {
  3133. ColumnsInternal.EnsureVisibleEdgedColumnsWidth();
  3134. InvalidateColumnHeadersMeasure();
  3135. InvalidateRowsMeasure(true);
  3136. InvalidateMeasure();
  3137. }
  3138. private void EnsureRowHeaderWidth()
  3139. {
  3140. if (AreRowHeadersVisible)
  3141. {
  3142. if (AreColumnHeadersVisible)
  3143. {
  3144. EnsureTopLeftCornerHeader();
  3145. }
  3146. if (_rowsPresenter != null)
  3147. {
  3148. bool updated = false;
  3149. foreach (Control element in _rowsPresenter.Children)
  3150. {
  3151. if (element is DataGridRow row)
  3152. {
  3153. // If the RowHeader resulted in a different width the last time it was measured, we need
  3154. // to re-measure it
  3155. if (row.HeaderCell != null && row.HeaderCell.DesiredSize.Width != ActualRowHeaderWidth)
  3156. {
  3157. row.HeaderCell.InvalidateMeasure();
  3158. updated = true;
  3159. }
  3160. }
  3161. else if (element is DataGridRowGroupHeader groupHeader && groupHeader.HeaderCell != null && groupHeader.HeaderCell.DesiredSize.Width != ActualRowHeaderWidth)
  3162. {
  3163. groupHeader.HeaderCell.InvalidateMeasure();
  3164. updated = true;
  3165. }
  3166. }
  3167. if (updated)
  3168. {
  3169. // We need to update the width of the horizontal scrollbar if the rowHeaders' width actually changed
  3170. InvalidateMeasure();
  3171. }
  3172. }
  3173. }
  3174. }
  3175. private void EnsureRowsPresenterVisibility()
  3176. {
  3177. if (_rowsPresenter != null)
  3178. {
  3179. // RowCount doesn't need to be considered, doing so might cause extra Visibility changes
  3180. _rowsPresenter.IsVisible = (ColumnsInternal.FirstVisibleNonFillerColumn != null);
  3181. }
  3182. }
  3183. private void EnsureTopLeftCornerHeader()
  3184. {
  3185. if (_topLeftCornerHeader != null)
  3186. {
  3187. _topLeftCornerHeader.IsVisible = (HeadersVisibility == DataGridHeadersVisibility.All);
  3188. if (_topLeftCornerHeader.IsVisible)
  3189. {
  3190. if (!double.IsNaN(RowHeaderWidth))
  3191. {
  3192. // RowHeaderWidth is set explicitly so we should use that
  3193. _topLeftCornerHeader.Width = RowHeaderWidth;
  3194. }
  3195. else if (VisibleSlotCount > 0)
  3196. {
  3197. // RowHeaders AutoSize and we have at least 1 row so take the desired width
  3198. _topLeftCornerHeader.Width = RowHeadersDesiredWidth;
  3199. }
  3200. }
  3201. }
  3202. }
  3203. private void InvalidateCellsArrange()
  3204. {
  3205. foreach (DataGridRow row in GetAllRows())
  3206. {
  3207. row.InvalidateHorizontalArrange();
  3208. }
  3209. }
  3210. private void InvalidateColumnHeadersArrange()
  3211. {
  3212. if (_columnHeadersPresenter != null)
  3213. {
  3214. _columnHeadersPresenter.InvalidateArrange();
  3215. }
  3216. }
  3217. private void InvalidateColumnHeadersMeasure()
  3218. {
  3219. if (_columnHeadersPresenter != null)
  3220. {
  3221. EnsureColumnHeadersVisibility();
  3222. _columnHeadersPresenter.InvalidateMeasure();
  3223. }
  3224. }
  3225. private void InvalidateRowsArrange()
  3226. {
  3227. if (_rowsPresenter != null)
  3228. {
  3229. _rowsPresenter.InvalidateArrange();
  3230. }
  3231. }
  3232. private void InvalidateRowsMeasure(bool invalidateIndividualElements)
  3233. {
  3234. if (_rowsPresenter != null)
  3235. {
  3236. _rowsPresenter.InvalidateMeasure();
  3237. if (invalidateIndividualElements)
  3238. {
  3239. foreach (Control element in _rowsPresenter.Children)
  3240. {
  3241. element.InvalidateMeasure();
  3242. }
  3243. }
  3244. }
  3245. }
  3246. //TODO: Make override?
  3247. private void DataGrid_GotFocus(object sender, RoutedEventArgs e)
  3248. {
  3249. if (!ContainsFocus)
  3250. {
  3251. ContainsFocus = true;
  3252. ApplyDisplayedRowsState(DisplayData.FirstScrollingSlot, DisplayData.LastScrollingSlot);
  3253. if (CurrentColumnIndex != -1 && IsSlotVisible(CurrentSlot))
  3254. {
  3255. if (DisplayData.GetDisplayedElement(CurrentSlot) is DataGridRow row)
  3256. {
  3257. row.Cells[CurrentColumnIndex].UpdatePseudoClasses();
  3258. }
  3259. }
  3260. }
  3261. // Keep track of which row contains the newly focused element
  3262. DataGridRow focusedRow = null;
  3263. IVisual focusedElement = e.Source as IVisual;
  3264. _focusedObject = focusedElement;
  3265. while (focusedElement != null)
  3266. {
  3267. focusedRow = focusedElement as DataGridRow;
  3268. if (focusedRow != null && focusedRow.OwningGrid == this && _focusedRow != focusedRow)
  3269. {
  3270. ResetFocusedRow();
  3271. _focusedRow = focusedRow.IsVisible ? focusedRow : null;
  3272. break;
  3273. }
  3274. focusedElement = focusedElement.GetVisualParent();
  3275. }
  3276. }
  3277. //TODO: Check
  3278. private void DataGrid_IsEnabledChanged(AvaloniaPropertyChangedEventArgs e)
  3279. {
  3280. }
  3281. private void DataGrid_KeyDown(object sender, KeyEventArgs e)
  3282. {
  3283. if (!e.Handled)
  3284. {
  3285. e.Handled = ProcessDataGridKey(e);
  3286. }
  3287. }
  3288. private void DataGrid_KeyUp(object sender, KeyEventArgs e)
  3289. {
  3290. if (e.Key == Key.Tab && CurrentColumnIndex != -1 && e.Source == this)
  3291. {
  3292. bool success =
  3293. ScrollSlotIntoView(
  3294. CurrentColumnIndex, CurrentSlot,
  3295. forCurrentCellChange: false,
  3296. forceHorizontalScroll: true);
  3297. Debug.Assert(success);
  3298. if (CurrentColumnIndex != -1 && SelectedItem == null)
  3299. {
  3300. SetRowSelection(CurrentSlot, isSelected: true, setAnchorSlot: true);
  3301. }
  3302. }
  3303. }
  3304. //TODO: Make override?
  3305. private void DataGrid_LostFocus(object sender, RoutedEventArgs e)
  3306. {
  3307. _focusedObject = null;
  3308. if (ContainsFocus)
  3309. {
  3310. bool focusLeftDataGrid = true;
  3311. bool dataGridWillReceiveRoutedEvent = true;
  3312. IVisual focusedObject = FocusManager.Instance.Current;
  3313. while (focusedObject != null)
  3314. {
  3315. if (focusedObject == this)
  3316. {
  3317. focusLeftDataGrid = false;
  3318. break;
  3319. }
  3320. // Walk up the visual tree. If we hit the root, try using the framework element's
  3321. // parent. We do this because Popups behave differently with respect to the visual tree,
  3322. // and it could have a parent even if the VisualTreeHelper doesn't find it.
  3323. IVisual parent = focusedObject.GetVisualParent();
  3324. if (parent == null)
  3325. {
  3326. if (focusedObject is Control element)
  3327. {
  3328. parent = element.Parent;
  3329. if (parent != null)
  3330. {
  3331. dataGridWillReceiveRoutedEvent = false;
  3332. }
  3333. }
  3334. }
  3335. focusedObject = parent;
  3336. }
  3337. if (focusLeftDataGrid)
  3338. {
  3339. ContainsFocus = false;
  3340. if (EditingRow != null)
  3341. {
  3342. CommitEdit(DataGridEditingUnit.Row, exitEditingMode: true);
  3343. }
  3344. ResetFocusedRow();
  3345. ApplyDisplayedRowsState(DisplayData.FirstScrollingSlot, DisplayData.LastScrollingSlot);
  3346. if (CurrentColumnIndex != -1 && IsSlotVisible(CurrentSlot))
  3347. {
  3348. if (DisplayData.GetDisplayedElement(CurrentSlot) is DataGridRow row)
  3349. {
  3350. row.Cells[CurrentColumnIndex].UpdatePseudoClasses();
  3351. }
  3352. }
  3353. }
  3354. else if (!dataGridWillReceiveRoutedEvent)
  3355. {
  3356. if (focusedObject is Control focusedElement)
  3357. {
  3358. focusedElement.LostFocus += ExternalEditingElement_LostFocus;
  3359. }
  3360. }
  3361. }
  3362. }
  3363. private void EditingElement_Initialized(object sender, EventArgs e)
  3364. {
  3365. var element = sender as Control;
  3366. if (element != null)
  3367. {
  3368. element.Initialized -= EditingElement_Initialized;
  3369. }
  3370. PreparingCellForEditPrivate(element);
  3371. }
  3372. //TODO Validation
  3373. //TODO Binding
  3374. //TODO TabStop
  3375. private bool EndCellEdit(DataGridEditAction editAction, bool exitEditingMode, bool keepFocus, bool raiseEvents)
  3376. {
  3377. if (_editingColumnIndex == -1)
  3378. {
  3379. return true;
  3380. }
  3381. Debug.Assert(EditingRow != null);
  3382. Debug.Assert(_editingColumnIndex >= 0);
  3383. Debug.Assert(_editingColumnIndex < ColumnsItemsInternal.Count);
  3384. Debug.Assert(_editingColumnIndex == CurrentColumnIndex);
  3385. Debug.Assert(EditingRow != null && EditingRow.Slot == CurrentSlot);
  3386. // Cache these to see if they change later
  3387. int currentSlot = CurrentSlot;
  3388. int currentColumnIndex = CurrentColumnIndex;
  3389. // We're ready to start ending, so raise the event
  3390. DataGridCell editingCell = EditingRow.Cells[_editingColumnIndex];
  3391. var editingElement = editingCell.Content as Control;
  3392. if (editingElement == null)
  3393. {
  3394. return false;
  3395. }
  3396. if (raiseEvents)
  3397. {
  3398. DataGridCellEditEndingEventArgs e = new DataGridCellEditEndingEventArgs(CurrentColumn, EditingRow, editingElement, editAction);
  3399. OnCellEditEnding(e);
  3400. if (e.Cancel)
  3401. {
  3402. // CellEditEnding has been cancelled
  3403. return false;
  3404. }
  3405. // Ensure that the current cell wasn't changed in the user's CellEditEnding handler
  3406. if (_editingColumnIndex == -1 ||
  3407. currentSlot != CurrentSlot ||
  3408. currentColumnIndex != CurrentColumnIndex)
  3409. {
  3410. return true;
  3411. }
  3412. Debug.Assert(EditingRow != null);
  3413. Debug.Assert(EditingRow.Slot == currentSlot);
  3414. Debug.Assert(_editingColumnIndex != -1);
  3415. Debug.Assert(_editingColumnIndex == CurrentColumnIndex);
  3416. }
  3417. // If we're canceling, let the editing column repopulate its old value if it wants
  3418. if (editAction == DataGridEditAction.Cancel)
  3419. {
  3420. CurrentColumn.CancelCellEditInternal(editingElement, _uneditedValue);
  3421. // Ensure that the current cell wasn't changed in the user column's CancelCellEdit
  3422. if (_editingColumnIndex == -1 ||
  3423. currentSlot != CurrentSlot ||
  3424. currentColumnIndex != CurrentColumnIndex)
  3425. {
  3426. return true;
  3427. }
  3428. Debug.Assert(EditingRow != null);
  3429. Debug.Assert(EditingRow.Slot == currentSlot);
  3430. Debug.Assert(_editingColumnIndex != -1);
  3431. Debug.Assert(_editingColumnIndex == CurrentColumnIndex);
  3432. }
  3433. // If we're committing, explicitly update the source but watch out for any validation errors
  3434. if (editAction == DataGridEditAction.Commit)
  3435. {
  3436. void SetValidationStatus(ICellEditBinding binding)
  3437. {
  3438. if (binding.IsValid)
  3439. {
  3440. ResetValidationStatus();
  3441. if (editingElement != null)
  3442. {
  3443. DataValidationErrors.ClearErrors(editingElement);
  3444. }
  3445. }
  3446. else
  3447. {
  3448. if (EditingRow != null)
  3449. {
  3450. if (editingCell.IsValid)
  3451. {
  3452. editingCell.IsValid = false;
  3453. editingCell.UpdatePseudoClasses();
  3454. }
  3455. if (EditingRow.IsValid)
  3456. {
  3457. EditingRow.IsValid = false;
  3458. EditingRow.UpdatePseudoClasses();
  3459. }
  3460. }
  3461. if (editingElement != null)
  3462. {
  3463. var errorList =
  3464. binding.ValidationErrors
  3465. .SelectMany(ex => ValidationUtil.UnpackException(ex))
  3466. .ToList();
  3467. DataValidationErrors.SetErrors(editingElement, errorList);
  3468. }
  3469. }
  3470. }
  3471. var editBinding = CurrentColumn?.CellEditBinding;
  3472. if (editBinding != null && !editBinding.CommitEdit())
  3473. {
  3474. SetValidationStatus(editBinding);
  3475. _validationSubscription?.Dispose();
  3476. _validationSubscription = editBinding.ValidationChanged.Subscribe(v => SetValidationStatus(editBinding));
  3477. ScrollSlotIntoView(CurrentColumnIndex, CurrentSlot, forCurrentCellChange: false, forceHorizontalScroll: true);
  3478. return false;
  3479. }
  3480. }
  3481. ResetValidationStatus();
  3482. if (exitEditingMode)
  3483. {
  3484. _editingColumnIndex = -1;
  3485. editingCell.UpdatePseudoClasses();
  3486. //IsTabStop = true;
  3487. if (keepFocus && editingElement.ContainsFocusedElement())
  3488. {
  3489. Focus();
  3490. }
  3491. PopulateCellContent(
  3492. isCellEdited: !exitEditingMode,
  3493. dataGridColumn: CurrentColumn,
  3494. dataGridRow: EditingRow,
  3495. dataGridCell: editingCell);
  3496. }
  3497. // We're done, so raise the CellEditEnded event
  3498. if (raiseEvents)
  3499. {
  3500. OnCellEditEnded(new DataGridCellEditEndedEventArgs(CurrentColumn, EditingRow, editAction));
  3501. }
  3502. // There's a chance that somebody reopened this cell for edit within the CellEditEnded handler,
  3503. // so we should return false if we were supposed to exit editing mode, but we didn't
  3504. return !(exitEditingMode && currentColumnIndex == _editingColumnIndex);
  3505. }
  3506. //TODO Validation
  3507. private bool EndRowEdit(DataGridEditAction editAction, bool exitEditingMode, bool raiseEvents)
  3508. {
  3509. if (EditingRow == null || DataConnection.CommittingEdit)
  3510. {
  3511. return true;
  3512. }
  3513. if (_editingColumnIndex != -1 || (editAction == DataGridEditAction.Cancel && raiseEvents &&
  3514. !((DataConnection.EditableCollectionView != null && DataConnection.EditableCollectionView.CanCancelEdit) || (EditingRow.DataContext is IEditableObject))))
  3515. {
  3516. // Ending the row edit will fail immediately under the following conditions:
  3517. // 1. We haven't ended the cell edit yet.
  3518. // 2. We're trying to cancel edit when the underlying DataType is not an IEditableObject,
  3519. // because we have no way to properly restore the old value. We will only allow this to occur
  3520. // if raiseEvents == false, which means we're internally forcing a cancel.
  3521. return false;
  3522. }
  3523. DataGridRow editingRow = EditingRow;
  3524. if (raiseEvents)
  3525. {
  3526. DataGridRowEditEndingEventArgs e = new DataGridRowEditEndingEventArgs(EditingRow, editAction);
  3527. OnRowEditEnding(e);
  3528. if (e.Cancel)
  3529. {
  3530. // RowEditEnding has been cancelled
  3531. return false;
  3532. }
  3533. // Editing states might have been changed in the RowEditEnding handlers
  3534. if (_editingColumnIndex != -1)
  3535. {
  3536. return false;
  3537. }
  3538. if (editingRow != EditingRow)
  3539. {
  3540. return true;
  3541. }
  3542. }
  3543. // Call the appropriate commit or cancel methods
  3544. if (editAction == DataGridEditAction.Commit)
  3545. {
  3546. if (!CommitRowEdit(exitEditingMode))
  3547. {
  3548. return false;
  3549. }
  3550. }
  3551. else
  3552. {
  3553. if (!CancelRowEdit(exitEditingMode) && raiseEvents)
  3554. {
  3555. // We failed to cancel edit so we should abort unless we're forcing a cancel
  3556. return false;
  3557. }
  3558. }
  3559. ResetValidationStatus();
  3560. // Update the previously edited row's state
  3561. if (exitEditingMode && editingRow == EditingRow)
  3562. {
  3563. RemoveEditingElements();
  3564. ResetEditingRow();
  3565. }
  3566. // Raise the RowEditEnded event
  3567. if (raiseEvents)
  3568. {
  3569. OnRowEditEnded(new DataGridRowEditEndedEventArgs(editingRow, editAction));
  3570. }
  3571. return true;
  3572. }
  3573. private void EnsureColumnHeadersVisibility()
  3574. {
  3575. if (_columnHeadersPresenter != null)
  3576. {
  3577. _columnHeadersPresenter.IsVisible = AreColumnHeadersVisible;
  3578. }
  3579. }
  3580. private void EnsureVerticalGridLines()
  3581. {
  3582. if (AreColumnHeadersVisible)
  3583. {
  3584. double totalColumnsWidth = 0;
  3585. foreach (DataGridColumn column in ColumnsInternal)
  3586. {
  3587. totalColumnsWidth += column.ActualWidth;
  3588. column.HeaderCell.AreSeparatorsVisible = (column != ColumnsInternal.LastVisibleColumn || totalColumnsWidth < CellsWidth);
  3589. }
  3590. }
  3591. foreach (DataGridRow row in GetAllRows())
  3592. {
  3593. row.EnsureGridLines();
  3594. }
  3595. }
  3596. /// <summary>
  3597. /// Exits editing mode without trying to commit or revert the editing, and
  3598. /// without repopulating the edited row's cell.
  3599. /// </summary>
  3600. //TODO TabStop
  3601. private void ExitEdit(bool keepFocus)
  3602. {
  3603. if (EditingRow == null || DataConnection.CommittingEdit)
  3604. {
  3605. Debug.Assert(_editingColumnIndex == -1);
  3606. return;
  3607. }
  3608. if (_editingColumnIndex != -1)
  3609. {
  3610. Debug.Assert(_editingColumnIndex >= 0);
  3611. Debug.Assert(_editingColumnIndex < ColumnsItemsInternal.Count);
  3612. Debug.Assert(_editingColumnIndex == CurrentColumnIndex);
  3613. Debug.Assert(EditingRow != null && EditingRow.Slot == CurrentSlot);
  3614. _editingColumnIndex = -1;
  3615. EditingRow.Cells[CurrentColumnIndex].UpdatePseudoClasses();
  3616. }
  3617. //IsTabStop = true;
  3618. if (IsSlotVisible(EditingRow.Slot))
  3619. {
  3620. EditingRow.UpdatePseudoClasses();
  3621. }
  3622. ResetEditingRow();
  3623. if (keepFocus)
  3624. {
  3625. Focus();
  3626. }
  3627. }
  3628. private void ExternalEditingElement_LostFocus(object sender, RoutedEventArgs e)
  3629. {
  3630. if (sender is Control element)
  3631. {
  3632. element.LostFocus -= ExternalEditingElement_LostFocus;
  3633. DataGrid_LostFocus(sender, e);
  3634. }
  3635. }
  3636. private void FlushCurrentCellChanged()
  3637. {
  3638. if (_makeFirstDisplayedCellCurrentCellPending)
  3639. {
  3640. return;
  3641. }
  3642. if (SelectionHasChanged)
  3643. {
  3644. // selection is changing, don't raise CurrentCellChanged until it's done
  3645. _flushCurrentCellChanged = true;
  3646. FlushSelectionChanged();
  3647. return;
  3648. }
  3649. // We don't want to expand all intermediate currency positions, so we only expand
  3650. // the last current item before we flush the event
  3651. if (_collapsedSlotsTable.Contains(CurrentSlot))
  3652. {
  3653. DataGridRowGroupInfo rowGroupInfo = RowGroupHeadersTable.GetValueAt(RowGroupHeadersTable.GetPreviousIndex(CurrentSlot));
  3654. Debug.Assert(rowGroupInfo != null);
  3655. if (rowGroupInfo != null)
  3656. {
  3657. ExpandRowGroupParentChain(rowGroupInfo.Level, rowGroupInfo.Slot);
  3658. }
  3659. }
  3660. if (CurrentColumn != _previousCurrentColumn
  3661. || CurrentItem != _previousCurrentItem)
  3662. {
  3663. CoerceSelectedItem();
  3664. _previousCurrentColumn = CurrentColumn;
  3665. _previousCurrentItem = CurrentItem;
  3666. OnCurrentCellChanged(EventArgs.Empty);
  3667. }
  3668. _flushCurrentCellChanged = false;
  3669. }
  3670. private void FlushSelectionChanged()
  3671. {
  3672. if (SelectionHasChanged && _noSelectionChangeCount == 0 && !_makeFirstDisplayedCellCurrentCellPending)
  3673. {
  3674. CoerceSelectedItem();
  3675. if (NoCurrentCellChangeCount != 0)
  3676. {
  3677. // current cell is changing, don't raise SelectionChanged until it's done
  3678. return;
  3679. }
  3680. SelectionHasChanged = false;
  3681. if (_flushCurrentCellChanged)
  3682. {
  3683. FlushCurrentCellChanged();
  3684. }
  3685. SelectionChangedEventArgs e = _selectedItems.GetSelectionChangedEventArgs();
  3686. if (e.AddedItems.Count > 0 || e.RemovedItems.Count > 0)
  3687. {
  3688. OnSelectionChanged(e);
  3689. }
  3690. }
  3691. }
  3692. //TODO TabStop
  3693. private bool FocusEditingCell(bool setFocus)
  3694. {
  3695. Debug.Assert(CurrentColumnIndex >= 0);
  3696. Debug.Assert(CurrentColumnIndex < ColumnsItemsInternal.Count);
  3697. Debug.Assert(CurrentSlot >= -1);
  3698. Debug.Assert(CurrentSlot < SlotCount);
  3699. Debug.Assert(EditingRow != null && EditingRow.Slot == CurrentSlot);
  3700. Debug.Assert(_editingColumnIndex != -1);
  3701. //IsTabStop = false;
  3702. _focusEditingControl = false;
  3703. bool success = false;
  3704. DataGridCell dataGridCell = EditingRow.Cells[_editingColumnIndex];
  3705. if (setFocus)
  3706. {
  3707. if (dataGridCell.ContainsFocusedElement())
  3708. {
  3709. success = true;
  3710. }
  3711. else
  3712. {
  3713. dataGridCell.Focus();
  3714. success = dataGridCell.ContainsFocusedElement();
  3715. }
  3716. //TODO Check
  3717. //success = dataGridCell.ContainsFocusedElement() ? true : dataGridCell.Focus();
  3718. _focusEditingControl = !success;
  3719. }
  3720. return success;
  3721. }
  3722. // Calculates the amount to scroll for the ScrollLeft button
  3723. // This is a method rather than a property to emphasize a calculation
  3724. private double GetHorizontalSmallScrollDecrease()
  3725. {
  3726. // If the first column is covered up, scroll to the start of it when the user clicks the left button
  3727. if (_negHorizontalOffset > 0)
  3728. {
  3729. return _negHorizontalOffset;
  3730. }
  3731. else
  3732. {
  3733. // The entire first column is displayed, show the entire previous column when the user clicks
  3734. // the left button
  3735. DataGridColumn previousColumn = ColumnsInternal.GetPreviousVisibleScrollingColumn(
  3736. ColumnsItemsInternal[DisplayData.FirstDisplayedScrollingCol]);
  3737. if (previousColumn != null)
  3738. {
  3739. return GetEdgedColumnWidth(previousColumn);
  3740. }
  3741. else
  3742. {
  3743. // There's no previous column so don't move
  3744. return 0;
  3745. }
  3746. }
  3747. }
  3748. // Calculates the amount to scroll for the ScrollRight button
  3749. // This is a method rather than a property to emphasize a calculation
  3750. private double GetHorizontalSmallScrollIncrease()
  3751. {
  3752. if (DisplayData.FirstDisplayedScrollingCol >= 0)
  3753. {
  3754. return GetEdgedColumnWidth(ColumnsItemsInternal[DisplayData.FirstDisplayedScrollingCol]) - _negHorizontalOffset;
  3755. }
  3756. return 0;
  3757. }
  3758. // Calculates the amount the ScrollDown button should scroll
  3759. // This is a method rather than a property to emphasize that calculations are taking place
  3760. private double GetVerticalSmallScrollIncrease()
  3761. {
  3762. if (DisplayData.FirstScrollingSlot >= 0)
  3763. {
  3764. return GetExactSlotElementHeight(DisplayData.FirstScrollingSlot) - NegVerticalOffset;
  3765. }
  3766. return 0;
  3767. }
  3768. private void HorizontalScrollBar_Scroll(object sender, ScrollEventArgs e)
  3769. {
  3770. ProcessHorizontalScroll(e.ScrollEventType);
  3771. }
  3772. private bool IsColumnOutOfBounds(int columnIndex)
  3773. {
  3774. return columnIndex >= ColumnsItemsInternal.Count || columnIndex < 0;
  3775. }
  3776. private bool IsInnerCellOutOfBounds(int columnIndex, int slot)
  3777. {
  3778. return IsColumnOutOfBounds(columnIndex) || IsSlotOutOfBounds(slot);
  3779. }
  3780. private bool IsInnerCellOutOfSelectionBounds(int columnIndex, int slot)
  3781. {
  3782. return IsColumnOutOfBounds(columnIndex) || IsSlotOutOfSelectionBounds(slot);
  3783. }
  3784. private bool IsSlotOutOfBounds(int slot)
  3785. {
  3786. return slot >= SlotCount || slot < -1 || _collapsedSlotsTable.Contains(slot);
  3787. }
  3788. private bool IsSlotOutOfSelectionBounds(int slot)
  3789. {
  3790. if (RowGroupHeadersTable.Contains(slot))
  3791. {
  3792. Debug.Assert(slot >= 0 && slot < SlotCount);
  3793. return false;
  3794. }
  3795. else
  3796. {
  3797. int rowIndex = RowIndexFromSlot(slot);
  3798. return rowIndex < 0 || rowIndex >= DataConnection.Count;
  3799. }
  3800. }
  3801. private void MakeFirstDisplayedCellCurrentCell()
  3802. {
  3803. if (CurrentColumnIndex != -1)
  3804. {
  3805. _makeFirstDisplayedCellCurrentCellPending = false;
  3806. _desiredCurrentColumnIndex = -1;
  3807. FlushCurrentCellChanged();
  3808. return;
  3809. }
  3810. if (SlotCount != SlotFromRowIndex(DataConnection.Count))
  3811. {
  3812. _makeFirstDisplayedCellCurrentCellPending = true;
  3813. return;
  3814. }
  3815. // No current cell, therefore no selection either - try to set the current cell to the
  3816. // ItemsSource's ICollectionView.CurrentItem if it exists, otherwise use the first displayed cell.
  3817. int slot = 0;
  3818. if (DataConnection.CollectionView != null)
  3819. {
  3820. if (DataConnection.CollectionView.IsCurrentBeforeFirst ||
  3821. DataConnection.CollectionView.IsCurrentAfterLast)
  3822. {
  3823. slot = RowGroupHeadersTable.Contains(0) ? 0 : -1;
  3824. }
  3825. else
  3826. {
  3827. slot = SlotFromRowIndex(DataConnection.CollectionView.CurrentPosition);
  3828. }
  3829. }
  3830. else
  3831. {
  3832. if (SelectedIndex == -1)
  3833. {
  3834. // Try to default to the first row
  3835. slot = SlotFromRowIndex(0);
  3836. if (!IsSlotVisible(slot))
  3837. {
  3838. slot = -1;
  3839. }
  3840. }
  3841. else
  3842. {
  3843. slot = SlotFromRowIndex(SelectedIndex);
  3844. }
  3845. }
  3846. int columnIndex = FirstDisplayedNonFillerColumnIndex;
  3847. if (_desiredCurrentColumnIndex >= 0 && _desiredCurrentColumnIndex < ColumnsItemsInternal.Count)
  3848. {
  3849. columnIndex = _desiredCurrentColumnIndex;
  3850. }
  3851. SetAndSelectCurrentCell(columnIndex, slot, forceCurrentCellSelection: false);
  3852. AnchorSlot = slot;
  3853. _makeFirstDisplayedCellCurrentCellPending = false;
  3854. _desiredCurrentColumnIndex = -1;
  3855. FlushCurrentCellChanged();
  3856. }
  3857. //TODO Styles
  3858. private void PopulateCellContent(bool isCellEdited,
  3859. DataGridColumn dataGridColumn,
  3860. DataGridRow dataGridRow,
  3861. DataGridCell dataGridCell)
  3862. {
  3863. Debug.Assert(dataGridColumn != null);
  3864. Debug.Assert(dataGridRow != null);
  3865. Debug.Assert(dataGridCell != null);
  3866. IControl element = null;
  3867. DataGridBoundColumn dataGridBoundColumn = dataGridColumn as DataGridBoundColumn;
  3868. if (isCellEdited)
  3869. {
  3870. // Generate EditingElement and apply column style if available
  3871. element = dataGridColumn.GenerateEditingElementInternal(dataGridCell, dataGridRow.DataContext);
  3872. if (element != null)
  3873. {
  3874. // Subscribe to the new element's events
  3875. element.Initialized += EditingElement_Initialized;
  3876. }
  3877. }
  3878. else
  3879. {
  3880. // Generate Element and apply column style if available
  3881. element = dataGridColumn.GenerateElementInternal(dataGridCell, dataGridRow.DataContext);
  3882. }
  3883. dataGridCell.Content = element;
  3884. }
  3885. private void PreparingCellForEditPrivate(Control editingElement)
  3886. {
  3887. if (_editingColumnIndex == -1 ||
  3888. CurrentColumnIndex == -1 ||
  3889. EditingRow.Cells[CurrentColumnIndex].Content != editingElement)
  3890. {
  3891. // The current cell has changed since the call to BeginCellEdit, so the fact
  3892. // that this element has loaded is no longer relevant
  3893. return;
  3894. }
  3895. Debug.Assert(EditingRow != null);
  3896. Debug.Assert(_editingColumnIndex >= 0);
  3897. Debug.Assert(_editingColumnIndex < ColumnsItemsInternal.Count);
  3898. Debug.Assert(_editingColumnIndex == CurrentColumnIndex);
  3899. Debug.Assert(EditingRow != null && EditingRow.Slot == CurrentSlot);
  3900. FocusEditingCell(setFocus: ContainsFocus || _focusEditingControl);
  3901. // Prepare the cell for editing and raise the PreparingCellForEdit event for all columns
  3902. DataGridColumn dataGridColumn = CurrentColumn;
  3903. _uneditedValue = dataGridColumn.PrepareCellForEditInternal(editingElement, _editingEventArgs);
  3904. OnPreparingCellForEdit(new DataGridPreparingCellForEditEventArgs(dataGridColumn, EditingRow, _editingEventArgs, editingElement));
  3905. }
  3906. private bool ProcessAKey(KeyEventArgs e)
  3907. {
  3908. KeyboardHelper.GetMetaKeyState(e.KeyModifiers, out bool ctrl, out bool shift, out bool alt);
  3909. if (ctrl && !shift && !alt && SelectionMode == DataGridSelectionMode.Extended)
  3910. {
  3911. SelectAll();
  3912. return true;
  3913. }
  3914. return false;
  3915. }
  3916. //TODO TabStop
  3917. //TODO FlowDirection
  3918. private bool ProcessDataGridKey(KeyEventArgs e)
  3919. {
  3920. bool focusDataGrid = false;
  3921. switch (e.Key)
  3922. {
  3923. case Key.Tab:
  3924. return ProcessTabKey(e);
  3925. case Key.Up:
  3926. focusDataGrid = ProcessUpKey(e);
  3927. break;
  3928. case Key.Down:
  3929. focusDataGrid = ProcessDownKey(e);
  3930. break;
  3931. case Key.PageDown:
  3932. focusDataGrid = ProcessNextKey(e);
  3933. break;
  3934. case Key.PageUp:
  3935. focusDataGrid = ProcessPriorKey(e);
  3936. break;
  3937. case Key.Left:
  3938. focusDataGrid = ProcessLeftKey(e);
  3939. break;
  3940. case Key.Right:
  3941. focusDataGrid = ProcessRightKey(e);
  3942. break;
  3943. case Key.F2:
  3944. return ProcessF2Key(e);
  3945. case Key.Home:
  3946. focusDataGrid = ProcessHomeKey(e);
  3947. break;
  3948. case Key.End:
  3949. focusDataGrid = ProcessEndKey(e);
  3950. break;
  3951. case Key.Enter:
  3952. focusDataGrid = ProcessEnterKey(e);
  3953. break;
  3954. case Key.Escape:
  3955. return ProcessEscapeKey();
  3956. case Key.A:
  3957. return ProcessAKey(e);
  3958. case Key.C:
  3959. return ProcessCopyKey(e.KeyModifiers);
  3960. case Key.Insert:
  3961. return ProcessCopyKey(e.KeyModifiers);
  3962. }
  3963. if (focusDataGrid)
  3964. {
  3965. Focus();
  3966. }
  3967. return focusDataGrid;
  3968. }
  3969. private bool ProcessDownKeyInternal(bool shift, bool ctrl)
  3970. {
  3971. DataGridColumn dataGridColumn = ColumnsInternal.FirstVisibleColumn;
  3972. int firstVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index;
  3973. int lastSlot = LastVisibleSlot;
  3974. if (firstVisibleColumnIndex == -1 || lastSlot == -1)
  3975. {
  3976. return false;
  3977. }
  3978. if (WaitForLostFocus(() => ProcessDownKeyInternal(shift, ctrl)))
  3979. {
  3980. return true;
  3981. }
  3982. int nextSlot = -1;
  3983. if (CurrentSlot != -1)
  3984. {
  3985. nextSlot = GetNextVisibleSlot(CurrentSlot);
  3986. if (nextSlot >= SlotCount)
  3987. {
  3988. nextSlot = -1;
  3989. }
  3990. }
  3991. _noSelectionChangeCount++;
  3992. try
  3993. {
  3994. int desiredSlot;
  3995. int columnIndex;
  3996. DataGridSelectionAction action;
  3997. if (CurrentColumnIndex == -1)
  3998. {
  3999. desiredSlot = FirstVisibleSlot;
  4000. columnIndex = firstVisibleColumnIndex;
  4001. action = DataGridSelectionAction.SelectCurrent;
  4002. }
  4003. else if (ctrl)
  4004. {
  4005. if (shift)
  4006. {
  4007. // Both Ctrl and Shift
  4008. desiredSlot = lastSlot;
  4009. columnIndex = CurrentColumnIndex;
  4010. action = (SelectionMode == DataGridSelectionMode.Extended)
  4011. ? DataGridSelectionAction.SelectFromAnchorToCurrent
  4012. : DataGridSelectionAction.SelectCurrent;
  4013. }
  4014. else
  4015. {
  4016. // Ctrl without Shift
  4017. desiredSlot = lastSlot;
  4018. columnIndex = CurrentColumnIndex;
  4019. action = DataGridSelectionAction.SelectCurrent;
  4020. }
  4021. }
  4022. else
  4023. {
  4024. if (nextSlot == -1)
  4025. {
  4026. return true;
  4027. }
  4028. if (shift)
  4029. {
  4030. // Shift without Ctrl
  4031. desiredSlot = nextSlot;
  4032. columnIndex = CurrentColumnIndex;
  4033. action = DataGridSelectionAction.SelectFromAnchorToCurrent;
  4034. }
  4035. else
  4036. {
  4037. // Neither Ctrl nor Shift
  4038. desiredSlot = nextSlot;
  4039. columnIndex = CurrentColumnIndex;
  4040. action = DataGridSelectionAction.SelectCurrent;
  4041. }
  4042. }
  4043. UpdateSelectionAndCurrency(columnIndex, desiredSlot, action, scrollIntoView: true);
  4044. }
  4045. finally
  4046. {
  4047. NoSelectionChangeCount--;
  4048. }
  4049. return _successfullyUpdatedSelection;
  4050. }
  4051. private bool ProcessEndKey(bool shift, bool ctrl)
  4052. {
  4053. DataGridColumn dataGridColumn = ColumnsInternal.LastVisibleColumn;
  4054. int lastVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index;
  4055. int firstVisibleSlot = FirstVisibleSlot;
  4056. int lastVisibleSlot = LastVisibleSlot;
  4057. if (lastVisibleColumnIndex == -1 || firstVisibleSlot == -1)
  4058. {
  4059. return false;
  4060. }
  4061. if (WaitForLostFocus(() => ProcessEndKey(shift, ctrl)))
  4062. {
  4063. return true;
  4064. }
  4065. _noSelectionChangeCount++;
  4066. try
  4067. {
  4068. if (!ctrl)
  4069. {
  4070. return ProcessRightMost(lastVisibleColumnIndex, firstVisibleSlot);
  4071. }
  4072. else
  4073. {
  4074. DataGridSelectionAction action = (shift && SelectionMode == DataGridSelectionMode.Extended)
  4075. ? DataGridSelectionAction.SelectFromAnchorToCurrent
  4076. : DataGridSelectionAction.SelectCurrent;
  4077. UpdateSelectionAndCurrency(lastVisibleColumnIndex, lastVisibleSlot, action, scrollIntoView: true);
  4078. }
  4079. }
  4080. finally
  4081. {
  4082. NoSelectionChangeCount--;
  4083. }
  4084. return _successfullyUpdatedSelection;
  4085. }
  4086. private bool ProcessEnterKey(bool shift, bool ctrl)
  4087. {
  4088. int oldCurrentSlot = CurrentSlot;
  4089. if (!ctrl)
  4090. {
  4091. // If Enter was used by a TextBox, we shouldn't handle the key
  4092. if (FocusManager.Instance.Current is TextBox focusedTextBox && focusedTextBox.AcceptsReturn)
  4093. {
  4094. return false;
  4095. }
  4096. if (WaitForLostFocus(() => ProcessEnterKey(shift, ctrl)))
  4097. {
  4098. return true;
  4099. }
  4100. // Enter behaves like down arrow - it commits the potential editing and goes down one cell.
  4101. if (!ProcessDownKeyInternal(false, ctrl))
  4102. {
  4103. return false;
  4104. }
  4105. }
  4106. else if (WaitForLostFocus(() => ProcessEnterKey(shift, ctrl)))
  4107. {
  4108. return true;
  4109. }
  4110. // Try to commit the potential editing
  4111. if (oldCurrentSlot == CurrentSlot &&
  4112. EndCellEdit(DataGridEditAction.Commit, exitEditingMode: true, keepFocus: true, raiseEvents: true) &&
  4113. EditingRow != null)
  4114. {
  4115. EndRowEdit(DataGridEditAction.Commit, exitEditingMode: true, raiseEvents: true);
  4116. ScrollIntoView(CurrentItem, CurrentColumn);
  4117. }
  4118. return true;
  4119. }
  4120. private bool ProcessEscapeKey()
  4121. {
  4122. if (WaitForLostFocus(() => ProcessEscapeKey()))
  4123. {
  4124. return true;
  4125. }
  4126. if (_editingColumnIndex != -1)
  4127. {
  4128. // Revert the potential cell editing and exit cell editing.
  4129. EndCellEdit(DataGridEditAction.Cancel, exitEditingMode: true, keepFocus: true, raiseEvents: true);
  4130. return true;
  4131. }
  4132. else if (EditingRow != null)
  4133. {
  4134. // Revert the potential row editing and exit row editing.
  4135. EndRowEdit(DataGridEditAction.Cancel, exitEditingMode: true, raiseEvents: true);
  4136. return true;
  4137. }
  4138. return false;
  4139. }
  4140. private bool ProcessF2Key(KeyEventArgs e)
  4141. {
  4142. KeyboardHelper.GetMetaKeyState(e.KeyModifiers, out bool ctrl, out bool shift);
  4143. if (!shift && !ctrl &&
  4144. _editingColumnIndex == -1 && CurrentColumnIndex != -1 && GetRowSelection(CurrentSlot) &&
  4145. !GetColumnEffectiveReadOnlyState(CurrentColumn))
  4146. {
  4147. if (ScrollSlotIntoView(CurrentColumnIndex, CurrentSlot, forCurrentCellChange: false, forceHorizontalScroll: true))
  4148. {
  4149. BeginCellEdit(e);
  4150. }
  4151. return true;
  4152. }
  4153. return false;
  4154. }
  4155. private bool ProcessHomeKey(bool shift, bool ctrl)
  4156. {
  4157. DataGridColumn dataGridColumn = ColumnsInternal.FirstVisibleNonFillerColumn;
  4158. int firstVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index;
  4159. int firstVisibleSlot = FirstVisibleSlot;
  4160. if (firstVisibleColumnIndex == -1 || firstVisibleSlot == -1)
  4161. {
  4162. return false;
  4163. }
  4164. if (WaitForLostFocus(() => ProcessHomeKey(shift, ctrl)))
  4165. {
  4166. return true;
  4167. }
  4168. _noSelectionChangeCount++;
  4169. try
  4170. {
  4171. if (!ctrl)
  4172. {
  4173. return ProcessLeftMost(firstVisibleColumnIndex, firstVisibleSlot);
  4174. }
  4175. else
  4176. {
  4177. DataGridSelectionAction action = (shift && SelectionMode == DataGridSelectionMode.Extended)
  4178. ? DataGridSelectionAction.SelectFromAnchorToCurrent
  4179. : DataGridSelectionAction.SelectCurrent;
  4180. UpdateSelectionAndCurrency(firstVisibleColumnIndex, firstVisibleSlot, action, scrollIntoView: true);
  4181. }
  4182. }
  4183. finally
  4184. {
  4185. NoSelectionChangeCount--;
  4186. }
  4187. return _successfullyUpdatedSelection;
  4188. }
  4189. private bool ProcessLeftKey(bool shift, bool ctrl)
  4190. {
  4191. DataGridColumn dataGridColumn = ColumnsInternal.FirstVisibleNonFillerColumn;
  4192. int firstVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index;
  4193. int firstVisibleSlot = FirstVisibleSlot;
  4194. if (firstVisibleColumnIndex == -1 || firstVisibleSlot == -1)
  4195. {
  4196. return false;
  4197. }
  4198. if (WaitForLostFocus(() => ProcessLeftKey(shift, ctrl)))
  4199. {
  4200. return true;
  4201. }
  4202. int previousVisibleColumnIndex = -1;
  4203. if (CurrentColumnIndex != -1)
  4204. {
  4205. dataGridColumn = ColumnsInternal.GetPreviousVisibleNonFillerColumn(ColumnsItemsInternal[CurrentColumnIndex]);
  4206. if (dataGridColumn != null)
  4207. {
  4208. previousVisibleColumnIndex = dataGridColumn.Index;
  4209. }
  4210. }
  4211. _noSelectionChangeCount++;
  4212. try
  4213. {
  4214. if (ctrl)
  4215. {
  4216. return ProcessLeftMost(firstVisibleColumnIndex, firstVisibleSlot);
  4217. }
  4218. else
  4219. {
  4220. if (RowGroupHeadersTable.Contains(CurrentSlot))
  4221. {
  4222. CollapseRowGroup(RowGroupHeadersTable.GetValueAt(CurrentSlot).CollectionViewGroup, collapseAllSubgroups: false);
  4223. }
  4224. else if (CurrentColumnIndex == -1)
  4225. {
  4226. UpdateSelectionAndCurrency(
  4227. firstVisibleColumnIndex,
  4228. firstVisibleSlot,
  4229. DataGridSelectionAction.SelectCurrent,
  4230. scrollIntoView: true);
  4231. }
  4232. else
  4233. {
  4234. if (previousVisibleColumnIndex == -1)
  4235. {
  4236. return true;
  4237. }
  4238. UpdateSelectionAndCurrency(
  4239. previousVisibleColumnIndex,
  4240. CurrentSlot,
  4241. DataGridSelectionAction.None,
  4242. scrollIntoView: true);
  4243. }
  4244. }
  4245. }
  4246. finally
  4247. {
  4248. NoSelectionChangeCount--;
  4249. }
  4250. return _successfullyUpdatedSelection;
  4251. }
  4252. // Ctrl Left <==> Home
  4253. private bool ProcessLeftMost(int firstVisibleColumnIndex, int firstVisibleSlot)
  4254. {
  4255. _noSelectionChangeCount++;
  4256. try
  4257. {
  4258. int desiredSlot;
  4259. DataGridSelectionAction action;
  4260. if (CurrentColumnIndex == -1)
  4261. {
  4262. desiredSlot = firstVisibleSlot;
  4263. action = DataGridSelectionAction.SelectCurrent;
  4264. Debug.Assert(_selectedItems.Count == 0);
  4265. }
  4266. else
  4267. {
  4268. desiredSlot = CurrentSlot;
  4269. action = DataGridSelectionAction.None;
  4270. }
  4271. UpdateSelectionAndCurrency(firstVisibleColumnIndex, desiredSlot, action, scrollIntoView: true);
  4272. }
  4273. finally
  4274. {
  4275. NoSelectionChangeCount--;
  4276. }
  4277. return _successfullyUpdatedSelection;
  4278. }
  4279. private bool ProcessNextKey(bool shift, bool ctrl)
  4280. {
  4281. DataGridColumn dataGridColumn = ColumnsInternal.FirstVisibleNonFillerColumn;
  4282. int firstVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index;
  4283. if (firstVisibleColumnIndex == -1 || DisplayData.FirstScrollingSlot == -1)
  4284. {
  4285. return false;
  4286. }
  4287. if (WaitForLostFocus(() => ProcessNextKey(shift, ctrl)))
  4288. {
  4289. return true;
  4290. }
  4291. int nextPageSlot = CurrentSlot == -1 ? DisplayData.FirstScrollingSlot : CurrentSlot;
  4292. Debug.Assert(nextPageSlot != -1);
  4293. int slot = GetNextVisibleSlot(nextPageSlot);
  4294. int scrollCount = DisplayData.NumTotallyDisplayedScrollingElements;
  4295. while (scrollCount > 0 && slot < SlotCount)
  4296. {
  4297. nextPageSlot = slot;
  4298. scrollCount--;
  4299. slot = GetNextVisibleSlot(slot);
  4300. }
  4301. _noSelectionChangeCount++;
  4302. try
  4303. {
  4304. DataGridSelectionAction action;
  4305. int columnIndex;
  4306. if (CurrentColumnIndex == -1)
  4307. {
  4308. columnIndex = firstVisibleColumnIndex;
  4309. action = DataGridSelectionAction.SelectCurrent;
  4310. }
  4311. else
  4312. {
  4313. columnIndex = CurrentColumnIndex;
  4314. action = (shift && SelectionMode == DataGridSelectionMode.Extended)
  4315. ? action = DataGridSelectionAction.SelectFromAnchorToCurrent
  4316. : action = DataGridSelectionAction.SelectCurrent;
  4317. }
  4318. UpdateSelectionAndCurrency(columnIndex, nextPageSlot, action, scrollIntoView: true);
  4319. }
  4320. finally
  4321. {
  4322. NoSelectionChangeCount--;
  4323. }
  4324. return _successfullyUpdatedSelection;
  4325. }
  4326. private bool ProcessPriorKey(bool shift, bool ctrl)
  4327. {
  4328. DataGridColumn dataGridColumn = ColumnsInternal.FirstVisibleNonFillerColumn;
  4329. int firstVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index;
  4330. if (firstVisibleColumnIndex == -1 || DisplayData.FirstScrollingSlot == -1)
  4331. {
  4332. return false;
  4333. }
  4334. if (WaitForLostFocus(() => ProcessPriorKey(shift, ctrl)))
  4335. {
  4336. return true;
  4337. }
  4338. int previousPageSlot = (CurrentSlot == -1) ? DisplayData.FirstScrollingSlot : CurrentSlot;
  4339. Debug.Assert(previousPageSlot != -1);
  4340. int scrollCount = DisplayData.NumTotallyDisplayedScrollingElements;
  4341. int slot = GetPreviousVisibleSlot(previousPageSlot);
  4342. while (scrollCount > 0 && slot != -1)
  4343. {
  4344. previousPageSlot = slot;
  4345. scrollCount--;
  4346. slot = GetPreviousVisibleSlot(slot);
  4347. }
  4348. Debug.Assert(previousPageSlot != -1);
  4349. _noSelectionChangeCount++;
  4350. try
  4351. {
  4352. int columnIndex;
  4353. DataGridSelectionAction action;
  4354. if (CurrentColumnIndex == -1)
  4355. {
  4356. columnIndex = firstVisibleColumnIndex;
  4357. action = DataGridSelectionAction.SelectCurrent;
  4358. }
  4359. else
  4360. {
  4361. columnIndex = CurrentColumnIndex;
  4362. action = (shift && SelectionMode == DataGridSelectionMode.Extended)
  4363. ? DataGridSelectionAction.SelectFromAnchorToCurrent
  4364. : DataGridSelectionAction.SelectCurrent;
  4365. }
  4366. UpdateSelectionAndCurrency(columnIndex, previousPageSlot, action, scrollIntoView: true);
  4367. }
  4368. finally
  4369. {
  4370. NoSelectionChangeCount--;
  4371. }
  4372. return _successfullyUpdatedSelection;
  4373. }
  4374. private bool ProcessRightKey(bool shift, bool ctrl)
  4375. {
  4376. DataGridColumn dataGridColumn = ColumnsInternal.LastVisibleColumn;
  4377. int lastVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index;
  4378. int firstVisibleSlot = FirstVisibleSlot;
  4379. if (lastVisibleColumnIndex == -1 || firstVisibleSlot == -1)
  4380. {
  4381. return false;
  4382. }
  4383. if (WaitForLostFocus(delegate { ProcessRightKey(shift, ctrl); }))
  4384. {
  4385. return true;
  4386. }
  4387. int nextVisibleColumnIndex = -1;
  4388. if (CurrentColumnIndex != -1)
  4389. {
  4390. dataGridColumn = ColumnsInternal.GetNextVisibleColumn(ColumnsItemsInternal[CurrentColumnIndex]);
  4391. if (dataGridColumn != null)
  4392. {
  4393. nextVisibleColumnIndex = dataGridColumn.Index;
  4394. }
  4395. }
  4396. _noSelectionChangeCount++;
  4397. try
  4398. {
  4399. if (ctrl)
  4400. {
  4401. return ProcessRightMost(lastVisibleColumnIndex, firstVisibleSlot);
  4402. }
  4403. else
  4404. {
  4405. if (RowGroupHeadersTable.Contains(CurrentSlot))
  4406. {
  4407. ExpandRowGroup(RowGroupHeadersTable.GetValueAt(CurrentSlot).CollectionViewGroup, expandAllSubgroups: false);
  4408. }
  4409. else if (CurrentColumnIndex == -1)
  4410. {
  4411. int firstVisibleColumnIndex = ColumnsInternal.FirstVisibleColumn == null ? -1 : ColumnsInternal.FirstVisibleColumn.Index;
  4412. UpdateSelectionAndCurrency(
  4413. firstVisibleColumnIndex,
  4414. firstVisibleSlot,
  4415. DataGridSelectionAction.SelectCurrent,
  4416. scrollIntoView: true);
  4417. }
  4418. else
  4419. {
  4420. if (nextVisibleColumnIndex == -1)
  4421. {
  4422. return true;
  4423. }
  4424. UpdateSelectionAndCurrency(
  4425. nextVisibleColumnIndex,
  4426. CurrentSlot,
  4427. DataGridSelectionAction.None,
  4428. scrollIntoView: true);
  4429. }
  4430. }
  4431. }
  4432. finally
  4433. {
  4434. NoSelectionChangeCount--;
  4435. }
  4436. return _successfullyUpdatedSelection;
  4437. }
  4438. // Ctrl Right <==> End
  4439. private bool ProcessRightMost(int lastVisibleColumnIndex, int firstVisibleSlot)
  4440. {
  4441. _noSelectionChangeCount++;
  4442. try
  4443. {
  4444. int desiredSlot;
  4445. DataGridSelectionAction action;
  4446. if (CurrentColumnIndex == -1)
  4447. {
  4448. desiredSlot = firstVisibleSlot;
  4449. action = DataGridSelectionAction.SelectCurrent;
  4450. }
  4451. else
  4452. {
  4453. desiredSlot = CurrentSlot;
  4454. action = DataGridSelectionAction.None;
  4455. }
  4456. UpdateSelectionAndCurrency(lastVisibleColumnIndex, desiredSlot, action, scrollIntoView: true);
  4457. }
  4458. finally
  4459. {
  4460. NoSelectionChangeCount--;
  4461. }
  4462. return _successfullyUpdatedSelection;
  4463. }
  4464. private bool ProcessTabKey(KeyEventArgs e)
  4465. {
  4466. KeyboardHelper.GetMetaKeyState(e.KeyModifiers, out bool ctrl, out bool shift);
  4467. return ProcessTabKey(e, shift, ctrl);
  4468. }
  4469. private bool ProcessTabKey(KeyEventArgs e, bool shift, bool ctrl)
  4470. {
  4471. if (ctrl || _editingColumnIndex == -1 || IsReadOnly)
  4472. {
  4473. //Go to the next/previous control on the page when
  4474. // - Ctrl key is used
  4475. // - Potential current cell is not edited, or the datagrid is read-only.
  4476. return false;
  4477. }
  4478. // Try to locate a writable cell before/after the current cell
  4479. Debug.Assert(CurrentColumnIndex != -1);
  4480. Debug.Assert(CurrentSlot != -1);
  4481. int neighborVisibleWritableColumnIndex, neighborSlot;
  4482. DataGridColumn dataGridColumn;
  4483. if (shift)
  4484. {
  4485. dataGridColumn = ColumnsInternal.GetPreviousVisibleWritableColumn(ColumnsItemsInternal[CurrentColumnIndex]);
  4486. neighborSlot = GetPreviousVisibleSlot(CurrentSlot);
  4487. if (EditingRow != null)
  4488. {
  4489. while (neighborSlot != -1 && RowGroupHeadersTable.Contains(neighborSlot))
  4490. {
  4491. neighborSlot = GetPreviousVisibleSlot(neighborSlot);
  4492. }
  4493. }
  4494. }
  4495. else
  4496. {
  4497. dataGridColumn = ColumnsInternal.GetNextVisibleWritableColumn(ColumnsItemsInternal[CurrentColumnIndex]);
  4498. neighborSlot = GetNextVisibleSlot(CurrentSlot);
  4499. if (EditingRow != null)
  4500. {
  4501. while (neighborSlot < SlotCount && RowGroupHeadersTable.Contains(neighborSlot))
  4502. {
  4503. neighborSlot = GetNextVisibleSlot(neighborSlot);
  4504. }
  4505. }
  4506. }
  4507. neighborVisibleWritableColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index;
  4508. if (neighborVisibleWritableColumnIndex == -1 && (neighborSlot == -1 || neighborSlot >= SlotCount))
  4509. {
  4510. // There is no previous/next row and no previous/next writable cell on the current row
  4511. return false;
  4512. }
  4513. if (WaitForLostFocus(() => ProcessTabKey(e, shift, ctrl)))
  4514. {
  4515. return true;
  4516. }
  4517. int targetSlot = -1, targetColumnIndex = -1;
  4518. _noSelectionChangeCount++;
  4519. try
  4520. {
  4521. if (neighborVisibleWritableColumnIndex == -1)
  4522. {
  4523. targetSlot = neighborSlot;
  4524. if (shift)
  4525. {
  4526. Debug.Assert(ColumnsInternal.LastVisibleWritableColumn != null);
  4527. targetColumnIndex = ColumnsInternal.LastVisibleWritableColumn.Index;
  4528. }
  4529. else
  4530. {
  4531. Debug.Assert(ColumnsInternal.FirstVisibleWritableColumn != null);
  4532. targetColumnIndex = ColumnsInternal.FirstVisibleWritableColumn.Index;
  4533. }
  4534. }
  4535. else
  4536. {
  4537. targetSlot = CurrentSlot;
  4538. targetColumnIndex = neighborVisibleWritableColumnIndex;
  4539. }
  4540. DataGridSelectionAction action;
  4541. if (targetSlot != CurrentSlot || (SelectionMode == DataGridSelectionMode.Extended))
  4542. {
  4543. if (IsSlotOutOfBounds(targetSlot))
  4544. {
  4545. return true;
  4546. }
  4547. action = DataGridSelectionAction.SelectCurrent;
  4548. }
  4549. else
  4550. {
  4551. action = DataGridSelectionAction.None;
  4552. }
  4553. UpdateSelectionAndCurrency(targetColumnIndex, targetSlot, action, scrollIntoView: true);
  4554. }
  4555. finally
  4556. {
  4557. NoSelectionChangeCount--;
  4558. }
  4559. if (_successfullyUpdatedSelection && !RowGroupHeadersTable.Contains(targetSlot))
  4560. {
  4561. BeginCellEdit(e);
  4562. }
  4563. // Return true to say we handled the key event even if the operation was unsuccessful. If we don't
  4564. // say we handled this event, the framework will continue to process the tab key and change focus.
  4565. return true;
  4566. }
  4567. private bool ProcessUpKey(bool shift, bool ctrl)
  4568. {
  4569. DataGridColumn dataGridColumn = ColumnsInternal.FirstVisibleNonFillerColumn;
  4570. int firstVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index;
  4571. int firstVisibleSlot = FirstVisibleSlot;
  4572. if (firstVisibleColumnIndex == -1 || firstVisibleSlot == -1)
  4573. {
  4574. return false;
  4575. }
  4576. if (WaitForLostFocus(() => ProcessUpKey(shift, ctrl)))
  4577. {
  4578. return true;
  4579. }
  4580. int previousVisibleSlot = (CurrentSlot != -1) ? GetPreviousVisibleSlot(CurrentSlot) : -1;
  4581. _noSelectionChangeCount++;
  4582. try
  4583. {
  4584. int slot;
  4585. int columnIndex;
  4586. DataGridSelectionAction action;
  4587. if (CurrentColumnIndex == -1)
  4588. {
  4589. slot = firstVisibleSlot;
  4590. columnIndex = firstVisibleColumnIndex;
  4591. action = DataGridSelectionAction.SelectCurrent;
  4592. }
  4593. else if (ctrl)
  4594. {
  4595. if (shift)
  4596. {
  4597. // Both Ctrl and Shift
  4598. slot = firstVisibleSlot;
  4599. columnIndex = CurrentColumnIndex;
  4600. action = (SelectionMode == DataGridSelectionMode.Extended)
  4601. ? DataGridSelectionAction.SelectFromAnchorToCurrent
  4602. : DataGridSelectionAction.SelectCurrent;
  4603. }
  4604. else
  4605. {
  4606. // Ctrl without Shift
  4607. slot = firstVisibleSlot;
  4608. columnIndex = CurrentColumnIndex;
  4609. action = DataGridSelectionAction.SelectCurrent;
  4610. }
  4611. }
  4612. else
  4613. {
  4614. if (previousVisibleSlot == -1)
  4615. {
  4616. return true;
  4617. }
  4618. if (shift)
  4619. {
  4620. // Shift without Ctrl
  4621. slot = previousVisibleSlot;
  4622. columnIndex = CurrentColumnIndex;
  4623. action = DataGridSelectionAction.SelectFromAnchorToCurrent;
  4624. }
  4625. else
  4626. {
  4627. // Neither Shift nor Ctrl
  4628. slot = previousVisibleSlot;
  4629. columnIndex = CurrentColumnIndex;
  4630. action = DataGridSelectionAction.SelectCurrent;
  4631. }
  4632. }
  4633. UpdateSelectionAndCurrency(columnIndex, slot, action, scrollIntoView: true);
  4634. }
  4635. finally
  4636. {
  4637. NoSelectionChangeCount--;
  4638. }
  4639. return _successfullyUpdatedSelection;
  4640. }
  4641. private void RemoveDisplayedColumnHeader(DataGridColumn dataGridColumn)
  4642. {
  4643. if (_columnHeadersPresenter != null)
  4644. {
  4645. _columnHeadersPresenter.Children.Remove(dataGridColumn.HeaderCell);
  4646. }
  4647. }
  4648. private void RemoveDisplayedColumnHeaders()
  4649. {
  4650. if (_columnHeadersPresenter != null)
  4651. {
  4652. _columnHeadersPresenter.Children.Clear();
  4653. }
  4654. ColumnsInternal.FillerColumn.IsRepresented = false;
  4655. }
  4656. private bool ResetCurrentCellCore()
  4657. {
  4658. return (CurrentColumnIndex == -1 || SetCurrentCellCore(-1, -1));
  4659. }
  4660. private void ResetEditingRow()
  4661. {
  4662. if (EditingRow != null
  4663. && EditingRow != _focusedRow
  4664. && !IsSlotVisible(EditingRow.Slot))
  4665. {
  4666. // Unload the old editing row if it's off screen
  4667. EditingRow.Clip = null;
  4668. UnloadRow(EditingRow);
  4669. DisplayData.FullyRecycleElements();
  4670. }
  4671. EditingRow = null;
  4672. }
  4673. private void ResetFocusedRow()
  4674. {
  4675. if (_focusedRow != null
  4676. && _focusedRow != EditingRow
  4677. && !IsSlotVisible(_focusedRow.Slot))
  4678. {
  4679. // Unload the old focused row if it's off screen
  4680. _focusedRow.Clip = null;
  4681. UnloadRow(_focusedRow);
  4682. DisplayData.FullyRecycleElements();
  4683. }
  4684. _focusedRow = null;
  4685. }
  4686. private void SelectAll()
  4687. {
  4688. SetRowsSelection(0, SlotCount - 1);
  4689. }
  4690. private void SetAndSelectCurrentCell(int columnIndex,
  4691. int slot,
  4692. bool forceCurrentCellSelection)
  4693. {
  4694. DataGridSelectionAction action = forceCurrentCellSelection ? DataGridSelectionAction.SelectCurrent : DataGridSelectionAction.None;
  4695. UpdateSelectionAndCurrency(columnIndex, slot, action, scrollIntoView: false);
  4696. }
  4697. // columnIndex = 2, rowIndex = -1 --> current cell belongs to the 'new row'.
  4698. // columnIndex = 2, rowIndex = 2 --> current cell is an inner cell
  4699. // columnIndex = -1, rowIndex = -1 --> current cell is reset
  4700. // columnIndex = -1, rowIndex = 2 --> Unexpected
  4701. private bool SetCurrentCellCore(int columnIndex, int slot, bool commitEdit, bool endRowEdit)
  4702. {
  4703. Debug.Assert(columnIndex < ColumnsItemsInternal.Count);
  4704. Debug.Assert(slot < SlotCount);
  4705. Debug.Assert(columnIndex == -1 || ColumnsItemsInternal[columnIndex].IsVisible);
  4706. Debug.Assert(!(columnIndex > -1 && slot == -1));
  4707. if (columnIndex == CurrentColumnIndex &&
  4708. slot == CurrentSlot)
  4709. {
  4710. Debug.Assert(DataConnection != null);
  4711. Debug.Assert(_editingColumnIndex == -1 || _editingColumnIndex == CurrentColumnIndex);
  4712. Debug.Assert(EditingRow == null || EditingRow.Slot == CurrentSlot || DataConnection.CommittingEdit);
  4713. return true;
  4714. }
  4715. Control oldDisplayedElement = null;
  4716. DataGridCellCoordinates oldCurrentCell = new DataGridCellCoordinates(CurrentCellCoordinates);
  4717. object newCurrentItem = null;
  4718. if (!RowGroupHeadersTable.Contains(slot))
  4719. {
  4720. int rowIndex = RowIndexFromSlot(slot);
  4721. if (rowIndex >= 0 && rowIndex < DataConnection.Count)
  4722. {
  4723. newCurrentItem = DataConnection.GetDataItem(rowIndex);
  4724. }
  4725. }
  4726. if (CurrentColumnIndex > -1)
  4727. {
  4728. Debug.Assert(CurrentColumnIndex < ColumnsItemsInternal.Count);
  4729. Debug.Assert(CurrentSlot < SlotCount);
  4730. if (!IsInnerCellOutOfBounds(oldCurrentCell.ColumnIndex, oldCurrentCell.Slot) &&
  4731. IsSlotVisible(oldCurrentCell.Slot))
  4732. {
  4733. oldDisplayedElement = DisplayData.GetDisplayedElement(oldCurrentCell.Slot);
  4734. }
  4735. if (!RowGroupHeadersTable.Contains(oldCurrentCell.Slot) && !_temporarilyResetCurrentCell)
  4736. {
  4737. bool keepFocus = ContainsFocus;
  4738. if (commitEdit)
  4739. {
  4740. if (!EndCellEdit(DataGridEditAction.Commit, exitEditingMode: true, keepFocus: keepFocus, raiseEvents: true))
  4741. {
  4742. return false;
  4743. }
  4744. // Resetting the current cell: setting it to (-1, -1) is not considered setting it out of bounds
  4745. if ((columnIndex != -1 && slot != -1 && IsInnerCellOutOfSelectionBounds(columnIndex, slot)) ||
  4746. IsInnerCellOutOfSelectionBounds(oldCurrentCell.ColumnIndex, oldCurrentCell.Slot))
  4747. {
  4748. return false;
  4749. }
  4750. if (endRowEdit && !EndRowEdit(DataGridEditAction.Commit, exitEditingMode: true, raiseEvents: true))
  4751. {
  4752. return false;
  4753. }
  4754. }
  4755. else
  4756. {
  4757. CancelEdit(DataGridEditingUnit.Row, false);
  4758. ExitEdit(keepFocus);
  4759. }
  4760. }
  4761. }
  4762. if (newCurrentItem != null)
  4763. {
  4764. slot = SlotFromRowIndex(DataConnection.IndexOf(newCurrentItem));
  4765. }
  4766. if (slot == -1 && columnIndex != -1)
  4767. {
  4768. return false;
  4769. }
  4770. CurrentColumnIndex = columnIndex;
  4771. CurrentSlot = slot;
  4772. if (_temporarilyResetCurrentCell)
  4773. {
  4774. if (columnIndex != -1)
  4775. {
  4776. _temporarilyResetCurrentCell = false;
  4777. }
  4778. }
  4779. if (!_temporarilyResetCurrentCell && _editingColumnIndex != -1)
  4780. {
  4781. _editingColumnIndex = columnIndex;
  4782. }
  4783. if (oldDisplayedElement != null)
  4784. {
  4785. if (oldDisplayedElement is DataGridRow row)
  4786. {
  4787. // Don't reset the state of the current cell if we're editing it because that would put it in an invalid state
  4788. UpdateCurrentState(oldDisplayedElement, oldCurrentCell.ColumnIndex, !(_temporarilyResetCurrentCell && row.IsEditing && _editingColumnIndex == oldCurrentCell.ColumnIndex));
  4789. }
  4790. else
  4791. {
  4792. UpdateCurrentState(oldDisplayedElement, oldCurrentCell.ColumnIndex, applyCellState: false);
  4793. }
  4794. }
  4795. if (CurrentColumnIndex > -1)
  4796. {
  4797. Debug.Assert(CurrentSlot > -1);
  4798. Debug.Assert(CurrentColumnIndex < ColumnsItemsInternal.Count);
  4799. Debug.Assert(CurrentSlot < SlotCount);
  4800. if (IsSlotVisible(CurrentSlot))
  4801. {
  4802. UpdateCurrentState(DisplayData.GetDisplayedElement(CurrentSlot), CurrentColumnIndex, applyCellState: true);
  4803. }
  4804. }
  4805. return true;
  4806. }
  4807. private void SetVerticalOffset(double newVerticalOffset)
  4808. {
  4809. _verticalOffset = newVerticalOffset;
  4810. if (_vScrollBar != null && !DoubleUtil.AreClose(newVerticalOffset, _vScrollBar.Value))
  4811. {
  4812. _vScrollBar.Value = _verticalOffset;
  4813. }
  4814. }
  4815. private void UpdateCurrentState(Control displayedElement, int columnIndex, bool applyCellState)
  4816. {
  4817. if (displayedElement is DataGridRow row)
  4818. {
  4819. if (AreRowHeadersVisible)
  4820. {
  4821. row.ApplyHeaderStatus();
  4822. }
  4823. DataGridCell cell = row.Cells[columnIndex];
  4824. if (applyCellState)
  4825. {
  4826. cell.UpdatePseudoClasses();
  4827. }
  4828. }
  4829. else if (displayedElement is DataGridRowGroupHeader groupHeader)
  4830. {
  4831. groupHeader.ApplyState(useTransitions: true);
  4832. if (AreRowHeadersVisible)
  4833. {
  4834. groupHeader.ApplyHeaderStatus();
  4835. }
  4836. }
  4837. }
  4838. private void UpdateHorizontalScrollBar(bool needHorizScrollbar, bool forceHorizScrollbar, double totalVisibleWidth, double totalVisibleFrozenWidth, double cellsWidth)
  4839. {
  4840. if (_hScrollBar != null)
  4841. {
  4842. if (needHorizScrollbar || forceHorizScrollbar)
  4843. {
  4844. // viewportSize
  4845. // v---v
  4846. //|<|_____|###|>|
  4847. // ^ ^
  4848. // min max
  4849. // we want to make the relative size of the thumb reflect the relative size of the viewing area
  4850. // viewportSize / (max + viewportSize) = cellsWidth / max
  4851. // -> viewportSize = max * cellsWidth / (max - cellsWidth)
  4852. // always zero
  4853. _hScrollBar.Minimum = 0;
  4854. if (needHorizScrollbar)
  4855. {
  4856. // maximum travel distance -- not the total width
  4857. _hScrollBar.Maximum = totalVisibleWidth - cellsWidth;
  4858. Debug.Assert(totalVisibleFrozenWidth >= 0);
  4859. if (_frozenColumnScrollBarSpacer != null)
  4860. {
  4861. _frozenColumnScrollBarSpacer.Width = totalVisibleFrozenWidth;
  4862. }
  4863. Debug.Assert(_hScrollBar.Maximum >= 0);
  4864. // width of the scrollable viewing area
  4865. double viewPortSize = Math.Max(0, cellsWidth - totalVisibleFrozenWidth);
  4866. _hScrollBar.ViewportSize = viewPortSize;
  4867. _hScrollBar.LargeChange = viewPortSize;
  4868. // The ScrollBar should be in sync with HorizontalOffset at this point. There's a resize case
  4869. // where the ScrollBar will coerce an old value here, but we don't want that
  4870. if (_hScrollBar.Value != _horizontalOffset)
  4871. {
  4872. _hScrollBar.Value = _horizontalOffset;
  4873. }
  4874. _hScrollBar.IsEnabled = true;
  4875. }
  4876. else
  4877. {
  4878. _hScrollBar.Maximum = 0;
  4879. _hScrollBar.ViewportSize = 0;
  4880. _hScrollBar.IsEnabled = false;
  4881. }
  4882. if (!_hScrollBar.IsVisible)
  4883. {
  4884. // This will trigger a call to this method via Cells_SizeChanged for
  4885. _ignoreNextScrollBarsLayout = true;
  4886. // which no processing is needed.
  4887. _hScrollBar.IsVisible = true;
  4888. if (_hScrollBar.DesiredSize.Height == 0)
  4889. {
  4890. // We need to know the height for the rest of layout to work correctly so measure it now
  4891. _hScrollBar.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
  4892. }
  4893. }
  4894. }
  4895. else
  4896. {
  4897. _hScrollBar.Maximum = 0;
  4898. if (_hScrollBar.IsVisible)
  4899. {
  4900. // This will trigger a call to this method via Cells_SizeChanged for
  4901. // which no processing is needed.
  4902. _hScrollBar.IsVisible = false;
  4903. _ignoreNextScrollBarsLayout = true;
  4904. }
  4905. }
  4906. }
  4907. }
  4908. private void UpdateVerticalScrollBar(bool needVertScrollbar, bool forceVertScrollbar, double totalVisibleHeight, double cellsHeight)
  4909. {
  4910. if (_vScrollBar != null)
  4911. {
  4912. if (needVertScrollbar || forceVertScrollbar)
  4913. {
  4914. // viewportSize
  4915. // v---v
  4916. //|<|_____|###|>|
  4917. // ^ ^
  4918. // min max
  4919. // we want to make the relative size of the thumb reflect the relative size of the viewing area
  4920. // viewportSize / (max + viewportSize) = cellsWidth / max
  4921. // -> viewportSize = max * cellsHeight / (totalVisibleHeight - cellsHeight)
  4922. // -> = max * cellsHeight / (totalVisibleHeight - cellsHeight)
  4923. // -> = max * cellsHeight / max
  4924. // -> = cellsHeight
  4925. // always zero
  4926. _vScrollBar.Minimum = 0;
  4927. if (needVertScrollbar && !double.IsInfinity(cellsHeight))
  4928. {
  4929. // maximum travel distance -- not the total height
  4930. _vScrollBar.Maximum = totalVisibleHeight - cellsHeight;
  4931. Debug.Assert(_vScrollBar.Maximum >= 0);
  4932. // total height of the display area
  4933. _vScrollBar.ViewportSize = cellsHeight;
  4934. _vScrollBar.IsEnabled = true;
  4935. }
  4936. else
  4937. {
  4938. _vScrollBar.Maximum = 0;
  4939. _vScrollBar.ViewportSize = 0;
  4940. _vScrollBar.IsEnabled = false;
  4941. }
  4942. if (!_vScrollBar.IsVisible)
  4943. {
  4944. // This will trigger a call to this method via Cells_SizeChanged for
  4945. // which no processing is needed.
  4946. _vScrollBar.IsVisible = true;
  4947. if (_vScrollBar.DesiredSize.Width == 0)
  4948. {
  4949. // We need to know the width for the rest of layout to work correctly so measure it now
  4950. _vScrollBar.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
  4951. }
  4952. _ignoreNextScrollBarsLayout = true;
  4953. }
  4954. }
  4955. else
  4956. {
  4957. _vScrollBar.Maximum = 0;
  4958. if (_vScrollBar.IsVisible)
  4959. {
  4960. // This will trigger a call to this method via Cells_SizeChanged for
  4961. // which no processing is needed.
  4962. _vScrollBar.IsVisible = false;
  4963. _ignoreNextScrollBarsLayout = true;
  4964. }
  4965. }
  4966. }
  4967. }
  4968. private void VerticalScrollBar_Scroll(object sender, ScrollEventArgs e)
  4969. {
  4970. ProcessVerticalScroll(e.ScrollEventType);
  4971. }
  4972. //TODO: Ensure left button is checked for
  4973. private bool UpdateStateOnMouseLeftButtonDown(PointerPressedEventArgs pointerPressedEventArgs, int columnIndex, int slot, bool allowEdit, bool shift, bool ctrl)
  4974. {
  4975. bool beginEdit;
  4976. Debug.Assert(slot >= 0);
  4977. // Before changing selection, check if the current cell needs to be committed, and
  4978. // check if the current row needs to be committed. If any of those two operations are required and fail,
  4979. // do not change selection, and do not change current cell.
  4980. bool wasInEdit = EditingColumnIndex != -1;
  4981. if (IsSlotOutOfBounds(slot))
  4982. {
  4983. return true;
  4984. }
  4985. if (wasInEdit && (columnIndex != EditingColumnIndex || slot != CurrentSlot) &&
  4986. WaitForLostFocus(() => UpdateStateOnMouseLeftButtonDown(pointerPressedEventArgs, columnIndex, slot, allowEdit, shift, ctrl)))
  4987. {
  4988. return true;
  4989. }
  4990. try
  4991. {
  4992. _noSelectionChangeCount++;
  4993. beginEdit = allowEdit &&
  4994. CurrentSlot == slot &&
  4995. columnIndex != -1 &&
  4996. (wasInEdit || CurrentColumnIndex == columnIndex) &&
  4997. !GetColumnEffectiveReadOnlyState(ColumnsItemsInternal[columnIndex]);
  4998. DataGridSelectionAction action;
  4999. if (SelectionMode == DataGridSelectionMode.Extended && shift)
  5000. {
  5001. // Shift select multiple rows
  5002. action = DataGridSelectionAction.SelectFromAnchorToCurrent;
  5003. }
  5004. else if (GetRowSelection(slot)) // Unselecting single row or Selecting a previously multi-selected row
  5005. {
  5006. if (!ctrl && SelectionMode == DataGridSelectionMode.Extended && _selectedItems.Count != 0)
  5007. {
  5008. // Unselect everything except the row that was clicked on
  5009. action = DataGridSelectionAction.SelectCurrent;
  5010. }
  5011. else if (ctrl && EditingRow == null)
  5012. {
  5013. action = DataGridSelectionAction.RemoveCurrentFromSelection;
  5014. }
  5015. else
  5016. {
  5017. action = DataGridSelectionAction.None;
  5018. }
  5019. }
  5020. else // Selecting a single row or multi-selecting with Ctrl
  5021. {
  5022. if (SelectionMode == DataGridSelectionMode.Single || !ctrl)
  5023. {
  5024. // Unselect the currectly selected rows except the new selected row
  5025. action = DataGridSelectionAction.SelectCurrent;
  5026. }
  5027. else
  5028. {
  5029. action = DataGridSelectionAction.AddCurrentToSelection;
  5030. }
  5031. }
  5032. UpdateSelectionAndCurrency(columnIndex, slot, action, scrollIntoView: false);
  5033. }
  5034. finally
  5035. {
  5036. NoSelectionChangeCount--;
  5037. }
  5038. if (_successfullyUpdatedSelection && beginEdit && BeginCellEdit(pointerPressedEventArgs))
  5039. {
  5040. FocusEditingCell(setFocus: true);
  5041. }
  5042. return true;
  5043. }
  5044. /// <summary>
  5045. /// Returns the Group at the indicated level or null if the item is not in the ItemsSource
  5046. /// </summary>
  5047. /// <param name="item">item</param>
  5048. /// <param name="groupLevel">groupLevel</param>
  5049. /// <returns>The group the given item falls under or null if the item is not in the ItemsSource</returns>
  5050. public DataGridCollectionViewGroup GetGroupFromItem(object item, int groupLevel)
  5051. {
  5052. int itemIndex = DataConnection.IndexOf(item);
  5053. if (itemIndex == -1)
  5054. {
  5055. return null;
  5056. }
  5057. int groupHeaderSlot = RowGroupHeadersTable.GetPreviousIndex(SlotFromRowIndex(itemIndex));
  5058. DataGridRowGroupInfo rowGroupInfo = RowGroupHeadersTable.GetValueAt(groupHeaderSlot);
  5059. while (rowGroupInfo != null && rowGroupInfo.Level != groupLevel)
  5060. {
  5061. groupHeaderSlot = RowGroupHeadersTable.GetPreviousIndex(rowGroupInfo.Slot);
  5062. rowGroupInfo = RowGroupHeadersTable.GetValueAt(groupHeaderSlot);
  5063. }
  5064. return rowGroupInfo?.CollectionViewGroup;
  5065. }
  5066. /// <summary>
  5067. /// Raises the LoadingRowGroup event
  5068. /// </summary>
  5069. /// <param name="e">EventArgs</param>
  5070. protected virtual void OnLoadingRowGroup(DataGridRowGroupHeaderEventArgs e)
  5071. {
  5072. EventHandler<DataGridRowGroupHeaderEventArgs> handler = LoadingRowGroup;
  5073. if (handler != null)
  5074. {
  5075. LoadingOrUnloadingRow = true;
  5076. handler(this, e);
  5077. LoadingOrUnloadingRow = false;
  5078. }
  5079. }
  5080. /// <summary>
  5081. /// Raises the UnLoadingRowGroup event
  5082. /// </summary>
  5083. /// <param name="e">EventArgs</param>
  5084. protected virtual void OnUnloadingRowGroup(DataGridRowGroupHeaderEventArgs e)
  5085. {
  5086. EventHandler<DataGridRowGroupHeaderEventArgs> handler = UnloadingRowGroup;
  5087. if (handler != null)
  5088. {
  5089. LoadingOrUnloadingRow = true;
  5090. handler(this, e);
  5091. LoadingOrUnloadingRow = false;
  5092. }
  5093. }
  5094. /// <summary>
  5095. /// Occurs before a DataGridRowGroupHeader header is used.
  5096. /// </summary>
  5097. public event EventHandler<DataGridRowGroupHeaderEventArgs> LoadingRowGroup;
  5098. /// <summary>
  5099. /// Occurs when the DataGridRowGroupHeader is available for reuse.
  5100. /// </summary>
  5101. public event EventHandler<DataGridRowGroupHeaderEventArgs> UnloadingRowGroup;
  5102. // Recursively expands parent RowGroupHeaders from the top down
  5103. private void ExpandRowGroupParentChain(int level, int slot)
  5104. {
  5105. if (level < 0)
  5106. {
  5107. return;
  5108. }
  5109. int previousHeaderSlot = RowGroupHeadersTable.GetPreviousIndex(slot + 1);
  5110. DataGridRowGroupInfo rowGroupInfo = null;
  5111. while (previousHeaderSlot >= 0)
  5112. {
  5113. rowGroupInfo = RowGroupHeadersTable.GetValueAt(previousHeaderSlot);
  5114. Debug.Assert(rowGroupInfo != null);
  5115. if (level == rowGroupInfo.Level)
  5116. {
  5117. if (_collapsedSlotsTable.Contains(rowGroupInfo.Slot))
  5118. {
  5119. // Keep going up the chain
  5120. ExpandRowGroupParentChain(level - 1, rowGroupInfo.Slot - 1);
  5121. }
  5122. if (!rowGroupInfo.IsVisible)
  5123. {
  5124. EnsureRowGroupVisibility(rowGroupInfo, true, false);
  5125. }
  5126. return;
  5127. }
  5128. else
  5129. {
  5130. previousHeaderSlot = RowGroupHeadersTable.GetPreviousIndex(previousHeaderSlot);
  5131. }
  5132. }
  5133. }
  5134. /// <summary>
  5135. /// This event is raised by OnCopyingRowClipboardContent method after the default row content is prepared.
  5136. /// Event listeners can modify or add to the row clipboard content.
  5137. /// </summary>
  5138. public event EventHandler<DataGridRowClipboardEventArgs> CopyingRowClipboardContent;
  5139. /// <summary>
  5140. /// This method raises the CopyingRowClipboardContent event.
  5141. /// </summary>
  5142. /// <param name="e">Contains the necessary information for generating the row clipboard content.</param>
  5143. protected virtual void OnCopyingRowClipboardContent(DataGridRowClipboardEventArgs e)
  5144. {
  5145. CopyingRowClipboardContent?.Invoke(this, e);
  5146. }
  5147. /// <summary>
  5148. /// This method formats a row (specified by a DataGridRowClipboardEventArgs) into
  5149. /// a single string to be added to the Clipboard when the DataGrid is copying its contents.
  5150. /// </summary>
  5151. /// <param name="e">DataGridRowClipboardEventArgs</param>
  5152. /// <returns>The formatted string.</returns>
  5153. private string FormatClipboardContent(DataGridRowClipboardEventArgs e)
  5154. {
  5155. StringBuilder text = new StringBuilder();
  5156. for (int cellIndex = 0; cellIndex < e.ClipboardRowContent.Count; cellIndex++)
  5157. {
  5158. DataGridClipboardCellContent cellContent = e.ClipboardRowContent[cellIndex];
  5159. if (cellContent != null)
  5160. {
  5161. text.Append(cellContent.Content);
  5162. }
  5163. if (cellIndex < e.ClipboardRowContent.Count - 1)
  5164. {
  5165. text.Append('\t');
  5166. }
  5167. else
  5168. {
  5169. text.Append('\r');
  5170. text.Append('\n');
  5171. }
  5172. }
  5173. return text.ToString();
  5174. }
  5175. /// <summary>
  5176. /// Handles the case where a 'Copy' key ('C' or 'Insert') has been pressed. If pressed in combination with
  5177. /// the control key, and the necessary prerequisites are met, the DataGrid will copy its contents
  5178. /// to the Clipboard as text.
  5179. /// </summary>
  5180. /// <returns>Whether or not the DataGrid handled the key press.</returns>
  5181. private bool ProcessCopyKey(KeyModifiers modifiers)
  5182. {
  5183. KeyboardHelper.GetMetaKeyState(modifiers, out bool ctrl, out bool shift, out bool alt);
  5184. if (ctrl && !shift && !alt && ClipboardCopyMode != DataGridClipboardCopyMode.None && SelectedItems.Count > 0)
  5185. {
  5186. StringBuilder textBuilder = new StringBuilder();
  5187. if (ClipboardCopyMode == DataGridClipboardCopyMode.IncludeHeader)
  5188. {
  5189. DataGridRowClipboardEventArgs headerArgs = new DataGridRowClipboardEventArgs(null, true);
  5190. foreach (DataGridColumn column in ColumnsInternal.GetVisibleColumns())
  5191. {
  5192. headerArgs.ClipboardRowContent.Add(new DataGridClipboardCellContent(null, column, column.Header));
  5193. }
  5194. OnCopyingRowClipboardContent(headerArgs);
  5195. textBuilder.Append(FormatClipboardContent(headerArgs));
  5196. }
  5197. for (int index = 0; index < SelectedItems.Count; index++)
  5198. {
  5199. object item = SelectedItems[index];
  5200. DataGridRowClipboardEventArgs itemArgs = new DataGridRowClipboardEventArgs(item, false);
  5201. foreach (DataGridColumn column in ColumnsInternal.GetVisibleColumns())
  5202. {
  5203. object content = column.GetCellValue(item, column.ClipboardContentBinding);
  5204. itemArgs.ClipboardRowContent.Add(new DataGridClipboardCellContent(item, column, content));
  5205. }
  5206. OnCopyingRowClipboardContent(itemArgs);
  5207. textBuilder.Append(FormatClipboardContent(itemArgs));
  5208. }
  5209. string text = textBuilder.ToString();
  5210. if (!string.IsNullOrEmpty(text))
  5211. {
  5212. CopyToClipboard(text);
  5213. return true;
  5214. }
  5215. }
  5216. return false;
  5217. }
  5218. private async void CopyToClipboard(string text)
  5219. {
  5220. var clipboard = ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard)));
  5221. await clipboard.SetTextAsync(text);
  5222. }
  5223. /// <summary>
  5224. /// This is an empty content control that's used during the DataGrid's copy procedure
  5225. /// to determine the value of a ClipboardContentBinding for a particular column and item.
  5226. /// </summary>
  5227. internal ContentControl ClipboardContentControl
  5228. {
  5229. get
  5230. {
  5231. if (_clipboardContentControl == null)
  5232. {
  5233. _clipboardContentControl = new ContentControl();
  5234. }
  5235. return _clipboardContentControl;
  5236. }
  5237. }
  5238. //TODO Validation UI
  5239. private void ResetValidationStatus()
  5240. {
  5241. // Clear the invalid status of the Cell, Row and DataGrid
  5242. if (EditingRow != null)
  5243. {
  5244. EditingRow.IsValid = true;
  5245. if (EditingRow.Index != -1)
  5246. {
  5247. foreach (DataGridCell cell in EditingRow.Cells)
  5248. {
  5249. if (!cell.IsValid)
  5250. {
  5251. cell.IsValid = true;
  5252. cell.UpdatePseudoClasses();
  5253. }
  5254. }
  5255. EditingRow.UpdatePseudoClasses();
  5256. }
  5257. }
  5258. IsValid = true;
  5259. _validationSubscription?.Dispose();
  5260. _validationSubscription = null;
  5261. }
  5262. /// <summary>
  5263. /// Raises the AutoGeneratingColumn event.
  5264. /// </summary>
  5265. protected virtual void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e)
  5266. {
  5267. AutoGeneratingColumn?.Invoke(this, e);
  5268. }
  5269. }
  5270. }