DataGrid.cs 230 KB

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