-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathReconciler.Update.cs
More file actions
4149 lines (3796 loc) · 189 KB
/
Reconciler.Update.cs
File metadata and controls
4149 lines (3796 loc) · 189 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.UI.Reactor.Animation;
using Microsoft.UI.Reactor.Core.Internal;
using Microsoft.UI.Reactor.Hosting;
using Microsoft.UI.Reactor.Controls.Validation;
using Microsoft.Extensions.Logging;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Hosting;
using Microsoft.UI.Xaml.Media.Imaging;
using WinUI = Microsoft.UI.Xaml.Controls;
using WinPrim = Microsoft.UI.Xaml.Controls.Primitives;
using WinShapes = Microsoft.UI.Xaml.Shapes;
using Windows.UI.WebUI;
namespace Microsoft.UI.Reactor.Core;
// AI-HINT: Reconciler.Update.cs — patches existing WinUI controls to match new Elements.
// Update() diffs old vs new Element and mutates the existing control in-place.
// Critical optimization: Element.ShallowEquals short-circuits when nothing changed.
// Returns null if existing control was patched; returns a new UIElement if the
// control type changed (caller must swap). Each UpdateXxx method mirrors its
// MountXxx counterpart but only touches properties that differ.
public sealed partial class Reconciler
{
/// <summary>
/// Diffs oldEl vs newEl and patches the existing control. Returns null if patched in-place,
/// or a replacement UIElement if the control type changed at runtime.
/// </summary>
private UIElement? Update(Element oldEl, Element newEl, UIElement control, Action requestRerender)
{
DebugElementsDiffed++;
// Unwrap all layers of ModifiedElement, accumulating modifiers.
// Inner modifiers override outer ones (via Merge: other wins where non-null).
ElementModifiers? oldModifiers = oldEl.Modifiers;
ElementModifiers? modifiers = newEl.Modifiers;
while (oldEl is ModifiedElement oldMod && newEl is ModifiedElement newMod)
{
oldModifiers = oldModifiers is not null
? oldModifiers.Merge(oldMod.WrappedModifiers)
: oldMod.WrappedModifiers;
modifiers = modifiers is not null
? modifiers.Merge(newMod.WrappedModifiers)
: newMod.WrappedModifiers;
oldEl = oldMod.Inner;
newEl = newMod.Inner;
}
// Merge any modifiers from the final inner element
if (oldEl.Modifiers is not null)
oldModifiers = oldModifiers is not null ? oldModifiers.Merge(oldEl.Modifiers) : oldEl.Modifiers;
if (newEl.Modifiers is not null)
modifiers = modifiers is not null ? modifiers.Merge(newEl.Modifiers) : newEl.Modifiers;
// Short-circuit: if old and new elements are structurally identical,
// skip all WinUI property access. This is the critical optimization for
// large grids where only a fraction of elements change each frame.
// Exception: elements with ThemeBindings must always re-apply because
// the resolved brush value depends on the control's effective theme,
// which can change independently of the element tree (e.g., parent
// RequestedTheme toggle).
// ReferenceEquals would fail constantly because fluent chains like
// .Width(200).Margin(10) produce a fresh ElementModifiers each render —
// identical values, new instance. Use structural equality so we skip
// when nothing actually changed.
//
// Callback-presence (oldEl.HasCallbacks == newEl.HasCallbacks) must
// also match: ShallowEquals ignores delegate identity, so a null→non-null
// OnClick transition would otherwise be skipped and the lazy-wire path
// in UpdateXxx never gets to attach the WinRT event. If presence
// changes, force Update so EnsureXxxWiring (poolable) or the diff-based
// null→non-null checks (non-poolable) can subscribe.
if (Element.ShallowEquals(oldEl, newEl)
&& Element.ModifiersEqual(oldModifiers, modifiers)
&& oldEl.HasCallbacks == newEl.HasCallbacks
&& !ForceRenderThroughWrapper(newEl))
{
DebugElementsSkipped++;
// Refresh Tag so the event trampoline dispatches into the new element's
// closure on next click/value-change. Gated on HasCallbacks so we skip
// the DependencyProperty write entirely for leaves with no handlers
// (TextBlock, Image, Border, etc.) — which is most of them.
if (newEl.HasCallbacks && control is FrameworkElement tagFeSE)
SetElementTag(tagFeSE, newEl);
if (newEl.ThemeBindings is not null && control is FrameworkElement thFeSE)
ApplyThemeBindings(thFeSE, newEl.ThemeBindings);
// Re-resolve ThemeRef-based resource overrides on theme change
if (newEl.ResourceOverrides is { ThemeRefs.Count: > 0 } && control is FrameworkElement resFeSE)
ApplyResourceOverrides(resFeSE, newEl.ResourceOverrides, newEl.ResourceOverrides);
return null; // null = keep existing control as-is
}
DebugUIElementsModified++;
// Push context values onto scope before processing children
var ctxValues = newEl.ContextValues;
int ctxCount = 0;
if (ctxValues is { Count: > 0 })
{
_contextScope.Push(ctxValues);
ctxCount = ctxValues.Count;
}
UIElement? result;
try
{
// Registered types checked first
if (_typeRegistry.TryGetValue(newEl.GetType(), out var reg))
{
result = reg.Update(oldEl, newEl, control, requestRerender, this);
}
else
{
result = (oldEl, newEl, control) switch
{
(TextBlockElement o, TextBlockElement n, TextBlock tb)
=> EnableBitmaskDiff ? UpdateTextBitmask(o, n, tb) : UpdateText(n, tb),
(RichTextBlockElement o, RichTextBlockElement n, WinUI.RichTextBlock rtb)
=> UpdateRichTextBlock(o, n, rtb),
(ButtonElement o, ButtonElement n, WinUI.Button b)
=> UpdateButton(o, n, b, requestRerender),
(HyperlinkButtonElement o, HyperlinkButtonElement n, WinUI.HyperlinkButton hb)
=> UpdateHyperlinkButton(o, n, hb),
(RepeatButtonElement o, RepeatButtonElement n, WinPrim.RepeatButton rb)
=> UpdateRepeatButton(o, n, rb),
(ToggleButtonElement o, ToggleButtonElement n, WinPrim.ToggleButton tb)
=> UpdateToggleButton(o, n, tb),
(DropDownButtonElement o, DropDownButtonElement n, WinUI.DropDownButton ddb)
=> UpdateDropDownButton(o, n, ddb, requestRerender),
(SplitButtonElement o, SplitButtonElement n, WinUI.SplitButton sb)
=> UpdateSplitButton(o, n, sb, requestRerender),
(ToggleSplitButtonElement o, ToggleSplitButtonElement n, WinUI.ToggleSplitButton tsb)
=> UpdateToggleSplitButton(o, n, tsb, requestRerender),
(RichEditBoxElement o, RichEditBoxElement n, WinUI.RichEditBox reb)
=> UpdateRichEditBox(o, n, reb),
(TextFieldElement o, TextFieldElement n, TextBox tb)
=> UpdateTextField(o, n, tb, requestRerender),
(PasswordBoxElement o, PasswordBoxElement n, WinUI.PasswordBox pb)
=> UpdatePasswordBox(o, n, pb),
(NumberBoxElement o, NumberBoxElement n, WinUI.NumberBox nb)
=> UpdateNumberBox(o, n, nb),
(AutoSuggestBoxElement o, AutoSuggestBoxElement n, WinUI.AutoSuggestBox asb)
=> UpdateAutoSuggestBox(o, n, asb),
(CheckBoxElement o, CheckBoxElement n, WinUI.CheckBox cb)
=> UpdateCheckBox(o, n, cb),
(RadioButtonElement o, RadioButtonElement n, WinUI.RadioButton rb)
=> UpdateRadioButton(o, n, rb),
(RadioButtonsElement o, RadioButtonsElement n, WinUI.RadioButtons rbg)
=> UpdateRadioButtons(o, n, rbg),
(ComboBoxElement o, ComboBoxElement n, WinUI.ComboBox cb)
=> UpdateComboBox(o, n, cb, requestRerender),
(SliderElement o, SliderElement n, WinUI.Slider s)
=> UpdateSlider(o, n, s),
(ToggleSwitchElement, ToggleSwitchElement n, WinUI.ToggleSwitch ts)
=> UpdateToggleSwitch(n, ts),
(RatingControlElement o, RatingControlElement n, WinUI.RatingControl r)
=> UpdateRatingControl(o, n, r),
(ColorPickerElement o, ColorPickerElement n, WinUI.ColorPicker cp)
=> UpdateColorPicker(o, n, cp),
(CalendarDatePickerElement o, CalendarDatePickerElement n, WinUI.CalendarDatePicker cdp)
=> UpdateCalendarDatePicker(o, n, cdp),
(DatePickerElement o, DatePickerElement n, WinUI.DatePicker dp)
=> UpdateDatePicker(o, n, dp),
(TimePickerElement o, TimePickerElement n, WinUI.TimePicker tp)
=> UpdateTimePicker(o, n, tp),
(ProgressElement, ProgressElement n, WinUI.ProgressBar pb)
=> UpdateProgress(n, pb),
(ProgressRingElement, ProgressRingElement n, WinUI.ProgressRing pr)
=> UpdateProgressRing(n, pr),
(ImageElement o, ImageElement n, WinUI.Image img)
=> UpdateImage(o, n, img),
(PersonPictureElement, PersonPictureElement n, WinUI.PersonPicture pp)
=> UpdatePersonPicture(n, pp),
(WebView2Element o, WebView2Element n, WinUI.WebView2 wv)
=> UpdateWebView2(o, n, wv),
(WrapGridElement o, WrapGridElement n, WinUI.VariableSizedWrapGrid wg)
=> UpdateWrapGrid(o, n, wg, requestRerender),
(StackElement o, StackElement n, WinUI.StackPanel sp)
=> UpdateStack(o, n, sp, requestRerender),
(ScrollViewerElement o, ScrollViewerElement n, WinUI.ScrollViewer sv)
=> UpdateScrollViewer(o, n, sv, newEl, requestRerender),
(ScrollViewElement o, ScrollViewElement n, WinUI.ScrollView sv)
=> UpdateScrollView(o, n, sv, newEl, requestRerender),
(BorderElement o, BorderElement n, WinUI.Border b)
=> UpdateBorder(o, n, b, newEl, requestRerender),
(ViewboxElement o, ViewboxElement n, WinUI.Viewbox vb)
=> UpdateViewbox(o, n, vb, requestRerender),
(ExpanderElement o, ExpanderElement n, WinUI.Expander exp)
=> UpdateExpander(o, n, exp, requestRerender),
(SplitViewElement o, SplitViewElement n, WinUI.SplitView sv)
=> UpdateSplitView(o, n, sv, requestRerender),
(NavigationHostElement o, NavigationHostElement n, WinUI.Grid navGrid)
=> UpdateNavigationHost(o, n, navGrid, requestRerender),
(NavigationViewElement o, NavigationViewElement n, WinUI.NavigationView nv)
=> UpdateNavigationView(o, n, nv, requestRerender),
(TitleBarElement o, TitleBarElement n, WinUI.TitleBar tb)
=> UpdateTitleBar(o, n, tb, requestRerender),
(TabViewElement o, TabViewElement n, WinUI.TabView tabView)
=> UpdateTabView(o, n, tabView, requestRerender),
(BreadcrumbBarElement o, BreadcrumbBarElement n, WinUI.BreadcrumbBar bcb)
=> UpdateBreadcrumbBar(o, n, bcb),
(PivotElement o, PivotElement n, WinUI.Pivot pivot)
=> UpdatePivot(o, n, pivot, requestRerender),
(ListViewElement o, ListViewElement n, WinUI.ListView lv)
=> UpdateListView(o, n, lv, requestRerender),
(GridViewElement o, GridViewElement n, WinUI.GridView gv)
=> UpdateGridView(o, n, gv, requestRerender),
(TreeViewElement o, TreeViewElement n, WinUI.TreeView tv)
=> UpdateTreeView(o, n, tv, requestRerender),
(FlipViewElement o, FlipViewElement n, WinUI.FlipView fv)
=> UpdateFlipView(o, n, fv, requestRerender),
(InfoBarElement o, InfoBarElement n, WinUI.InfoBar ib)
=> UpdateInfoBar(o, n, ib, requestRerender),
(InfoBadgeElement, InfoBadgeElement n, WinUI.InfoBadge badge)
=> UpdateInfoBadge(n, badge),
(ContentDialogElement o, ContentDialogElement n, FrameworkElement cdFe)
=> UpdateContentDialog(o, n, cdFe, requestRerender),
(TeachingTipElement o, TeachingTipElement n, WinUI.TeachingTip tip)
=> UpdateTeachingTip(o, n, tip, requestRerender),
(MenuBarElement o, MenuBarElement n, WinUI.MenuBar mb)
=> UpdateMenuBar(o, n, mb),
(CommandHostElement o, CommandHostElement n, WinUI.Grid chGrid)
=> UpdateCommandHost(o, n, chGrid, requestRerender),
(CommandBarElement o, CommandBarElement n, WinUI.CommandBar cb)
=> UpdateCommandBar(o, n, cb, requestRerender),
(Core.GridElement o, Core.GridElement n, WinUI.Grid g)
=> UpdateGrid(o, n, g, requestRerender),
(CanvasElement o, CanvasElement n, WinUI.Canvas cvs)
=> UpdateCanvas(o, n, cvs, requestRerender),
(FlexElement o, FlexElement n, Layout.FlexPanel fp)
=> UpdateFlex(o, n, fp, requestRerender),
(TemplatedListElementBase o, TemplatedListElementBase n, WinUI.ListView lv)
=> UpdateTemplatedListView(o, n, lv, requestRerender),
(TemplatedListElementBase o, TemplatedListElementBase n, WinUI.GridView gv)
=> UpdateTemplatedGridView(o, n, gv, requestRerender),
(TemplatedListElementBase o, TemplatedListElementBase n, WinUI.FlipView fv)
=> UpdateTemplatedFlipView(o, n, fv, requestRerender),
(LazyStackElementBase, LazyStackElementBase n, WinUI.ScrollViewer sv)
=> UpdateLazyStack(n, sv, requestRerender),
(RectangleElement, RectangleElement n, WinShapes.Rectangle r)
=> UpdateRectangle(n, r),
(EllipseElement, EllipseElement n, WinShapes.Ellipse e)
=> UpdateEllipse(n, e),
(LineElement, LineElement n, WinShapes.Line l)
=> UpdateLine(n, l),
(PathElement o, PathElement n, WinShapes.Path p)
=> UpdatePath(o, n, p),
(RelativePanelElement o, RelativePanelElement n, WinUI.RelativePanel rp)
=> UpdateRelativePanel(o, n, rp, requestRerender),
(MediaPlayerElementElement, MediaPlayerElementElement n, WinUI.MediaPlayerElement mpe)
=> UpdateMediaPlayerElement(n, mpe),
(AnimatedVisualPlayerElement, AnimatedVisualPlayerElement n, WinUI.AnimatedVisualPlayer avp)
=> UpdateAnimatedVisualPlayer(n, avp),
(SemanticZoomElement o, SemanticZoomElement n, WinUI.SemanticZoom sz)
=> UpdateSemanticZoom(o, n, sz, requestRerender),
(ListBoxElement o, ListBoxElement n, WinUI.ListBox lb)
=> UpdateListBox(o, n, lb),
(SelectorBarElement o, SelectorBarElement n, WinUI.SelectorBar sbar)
=> UpdateSelectorBar(o, n, sbar),
(PipsPagerElement o, PipsPagerElement n, WinUI.PipsPager pp)
=> UpdatePipsPager(o, n, pp),
(AnnotatedScrollBarElement, AnnotatedScrollBarElement n, WinUI.AnnotatedScrollBar asb)
=> UpdateAnnotatedScrollBar(n, asb),
(PopupElement o, PopupElement n, WinUI.StackPanel popupWrap)
=> UpdatePopup(o, n, popupWrap, requestRerender),
(RefreshContainerElement o, RefreshContainerElement n, WinUI.RefreshContainer rc)
=> UpdateRefreshContainer(o, n, rc, requestRerender),
(MenuFlyoutElement o, MenuFlyoutElement n, UIElement mfTarget)
=> UpdateMenuFlyout(o, n, mfTarget, requestRerender),
(FlyoutElement o, FlyoutElement n, UIElement flyTarget)
=> UpdateFlyoutElement(o, n, flyTarget, requestRerender),
(CommandBarFlyoutElement o, CommandBarFlyoutElement n, UIElement cbfTarget)
=> UpdateCommandBarFlyout(o, n, cbfTarget, requestRerender),
(CalendarViewElement, CalendarViewElement n, WinUI.CalendarView cv)
=> UpdateCalendarView(n, cv),
(SwipeControlElement o, SwipeControlElement n, WinUI.SwipeControl swipe)
=> UpdateSwipeControl(o, n, swipe, requestRerender),
(AnimatedIconElement, AnimatedIconElement n, WinUI.AnimatedIcon ai)
=> UpdateAnimatedIcon(n, ai),
(IconElement, IconElement n, WinUI.IconElement icon)
=> UpdateIcon(n, icon),
(ParallaxViewElement o, ParallaxViewElement n, WinUI.ParallaxView pv)
=> UpdateParallaxView(o, n, pv, requestRerender),
(MapControlElement, MapControlElement n, WinUI.MapControl mc)
=> UpdateMapControl(n, mc),
(FrameElement, FrameElement n, WinUI.Frame f)
=> UpdateFrame(n, f),
(ErrorBoundaryElement oldEb, ErrorBoundaryElement newEb, Border)
=> UpdateErrorBoundary(oldEb, newEb, control, requestRerender),
(FormFieldElement oldFf, FormFieldElement newFf, WinUI.StackPanel sp)
=> UpdateFormField(oldFf, newFf, sp, requestRerender),
(ValidationVisualizerElement oldVv, ValidationVisualizerElement newVv, WinUI.StackPanel sp)
=> UpdateValidationVisualizer(oldVv, newVv, sp, requestRerender),
(ValidationRuleElement, ValidationRuleElement n, WinUI.StackPanel)
=> UpdateValidationRule(n),
(SemanticElement oldSem, SemanticElement newSem, Accessibility.SemanticPanel sp)
=> UpdateSemantic(oldSem, newSem, sp, requestRerender),
(Hooks.AnnounceRegionElement, Hooks.AnnounceRegionElement, TextBlock)
=> null, // static element — nothing to update
(XamlHostElement, XamlHostElement n, FrameworkElement hostCtrl)
=> UpdateXamlHost(n, hostCtrl),
(XamlPageElement o, XamlPageElement n, WinUI.Frame f)
=> UpdateXamlPage(o, n, f),
(ComponentElement, ComponentElement, _)
=> UpdateComponent(oldEl, newEl, control, requestRerender),
(FuncElement, FuncElement, _)
=> UpdateComponent(oldEl, newEl, control, requestRerender),
(MemoElement, MemoElement, _)
=> UpdateComponent(oldEl, newEl, control, requestRerender),
_ => Mount(newEl, requestRerender),
};
}
// Apply inline modifiers after update. When old modifiers existed but new
// modifiers are null, pass an empty instance so ApplyModifiers can clear
// stale values (same principle as the flex attached-property fix).
var target = result ?? control;
// Record the control for highlight overlay only when the element's own
// WinUI properties were actually updated (not just children recursed).
// Containers whose only change is children references are excluded — the
// individual children will be captured if they change.
if (result is null && ReactorFeatureFlags.HighlightReconcileChanges
&& _highlightModified is not null
&& (!Element.OwnPropsEqual(oldEl, newEl) || !Element.ModifiersEqual(oldModifiers, modifiers)))
_highlightModified.Add(control);
if ((modifiers is not null || oldModifiers is not null) && target is FrameworkElement fe)
ApplyModifiers(fe, oldModifiers, modifiers ?? new ElementModifiers(), requestRerender);
// Re-apply the caption-derived default after modifiers have run so a
// label change ("+ 1" → "+ 2") updates UIA Name when the author never
// set an explicit name. No-ops when the author did.
if (target is FrameworkElement captionFe)
UpdateDefaultAutomationName(
captionFe,
ResolveCaptionForElement(oldEl),
ResolveCaptionForElement(newEl));
// Apply theme-resource bindings (ThemeRef → resolved Brush from WinUI resources)
if (newEl.ThemeBindings is not null && target is FrameworkElement thFe)
ApplyThemeBindings(thFe, newEl.ThemeBindings);
// Apply per-control resource overrides (lightweight styling)
if ((newEl.ResourceOverrides is not null || oldEl.ResourceOverrides is not null) && target is FrameworkElement resFe)
ApplyResourceOverrides(resFe, oldEl.ResourceOverrides, newEl.ResourceOverrides);
// Apply transitions after update (re-applies when transition config changes)
if (newEl.ImplicitTransitions is not null || newEl.ThemeTransitions is not null)
ApplyTransitions(target, newEl.ImplicitTransitions, newEl.ThemeTransitions);
// Apply or clear Composition-layer layout animation
if (newEl.LayoutAnimation is not null)
ApplyLayoutAnimation(target, newEl.LayoutAnimation);
else if (oldEl.LayoutAnimation is not null)
ClearLayoutAnimation(target);
// Apply or clear compositor property animation (.Animate() modifier)
if (newEl.AnimationConfig is not null)
ApplyPropertyAnimation(target, newEl.AnimationConfig, newEl.LayoutAnimation);
else if (oldEl.AnimationConfig is not null)
ClearPropertyAnimation(target, newEl.LayoutAnimation);
// Apply or clear interaction states (.InteractionStates() modifier)
if (newEl.InteractionStates is not null)
ApplyInteractionStates(target, newEl.InteractionStates);
else if (oldEl.InteractionStates is not null)
ClearInteractionStates(target);
// Apply keyframe animations (.Keyframes() modifier)
if (newEl.KeyframeAnimations is not null)
ApplyKeyframeAnimations(target, newEl.KeyframeAnimations);
else if (oldEl.KeyframeAnimations is not null)
ClearKeyframeAnimations(target, oldEl.KeyframeAnimations);
// Apply or clear scroll-linked expression animations (.ScrollLinked() modifier)
if (newEl.ScrollAnimation is not null)
ApplyScrollAnimation(target, newEl.ScrollAnimation);
else if (oldEl.ScrollAnimation is not null)
ClearScrollAnimation(target, oldEl.ScrollAnimation);
// Apply stagger delays to children (.Stagger() modifier)
if (newEl.StaggerConfig is not null)
ApplyStaggerDelays(target, newEl.StaggerConfig);
}
finally
{
if (ctxCount > 0)
_contextScope.Pop(ctxCount);
}
return result;
}
private UIElement? UpdateText(TextBlockElement n, TextBlock tb)
{
if (tb.Text != n.Content) tb.Text = n.Content;
if (n.FontSize.HasValue && tb.FontSize != n.FontSize.Value) tb.FontSize = n.FontSize.Value;
if (n.Weight.HasValue && tb.FontWeight.Weight != n.Weight.Value.Weight) tb.FontWeight = n.Weight.Value;
if (n.FontStyle.HasValue && tb.FontStyle != n.FontStyle.Value) tb.FontStyle = n.FontStyle.Value;
if (n.HorizontalAlignment.HasValue && tb.HorizontalAlignment != n.HorizontalAlignment.Value) tb.HorizontalAlignment = n.HorizontalAlignment.Value;
if (n.TextWrapping.HasValue && tb.TextWrapping != n.TextWrapping.Value) tb.TextWrapping = n.TextWrapping.Value;
if (n.TextAlignment.HasValue && tb.TextAlignment != n.TextAlignment.Value) tb.TextAlignment = n.TextAlignment.Value;
if (n.TextTrimming.HasValue && tb.TextTrimming != n.TextTrimming.Value) tb.TextTrimming = n.TextTrimming.Value;
if (n.IsTextSelectionEnabled.HasValue && tb.IsTextSelectionEnabled != n.IsTextSelectionEnabled.Value) tb.IsTextSelectionEnabled = n.IsTextSelectionEnabled.Value;
if (n.FontFamily is not null && tb.FontFamily != n.FontFamily) tb.FontFamily = n.FontFamily;
if (n.LineHeight.HasValue && tb.LineHeight != n.LineHeight.Value) tb.LineHeight = n.LineHeight.Value;
if (tb.MaxLines != n.MaxLines) tb.MaxLines = n.MaxLines;
if (tb.CharacterSpacing != n.CharacterSpacing) tb.CharacterSpacing = n.CharacterSpacing;
if (tb.TextDecorations != n.TextDecorations) tb.TextDecorations = n.TextDecorations;
ApplySetters(n.Setters, tb);
return null;
}
/// <summary>
/// EXP-2: Bitmask-based UpdateText — compares old vs new TextBlockElement (pure C#)
/// to determine which properties changed, then only touches those WinUI properties.
/// Avoids COM interop reads for unchanged properties.
/// </summary>
private UIElement? UpdateTextBitmask(TextBlockElement old, TextBlockElement n, TextBlock tb)
{
var diff = TextBlockElement.DiffProps(old, n);
if (diff == TextPropChanged.None) return null;
if ((diff & TextPropChanged.Content) != 0) tb.Text = n.Content;
if ((diff & TextPropChanged.FontSize) != 0 && n.FontSize.HasValue) tb.FontSize = n.FontSize.Value;
if ((diff & TextPropChanged.Weight) != 0 && n.Weight.HasValue) tb.FontWeight = n.Weight.Value;
if ((diff & TextPropChanged.FontStyle) != 0 && n.FontStyle.HasValue) tb.FontStyle = n.FontStyle.Value;
if ((diff & TextPropChanged.HorizontalAlignment) != 0 && n.HorizontalAlignment.HasValue) tb.HorizontalAlignment = n.HorizontalAlignment.Value;
if ((diff & TextPropChanged.TextWrapping) != 0 && n.TextWrapping.HasValue) tb.TextWrapping = n.TextWrapping.Value;
if ((diff & TextPropChanged.TextAlignment) != 0 && n.TextAlignment.HasValue) tb.TextAlignment = n.TextAlignment.Value;
if ((diff & TextPropChanged.TextTrimming) != 0 && n.TextTrimming.HasValue) tb.TextTrimming = n.TextTrimming.Value;
if ((diff & TextPropChanged.IsTextSelectionEnabled) != 0 && n.IsTextSelectionEnabled.HasValue) tb.IsTextSelectionEnabled = n.IsTextSelectionEnabled.Value;
if ((diff & TextPropChanged.FontFamily) != 0 && n.FontFamily is not null) tb.FontFamily = n.FontFamily;
if ((diff & TextPropChanged.LineHeight) != 0 && n.LineHeight.HasValue) tb.LineHeight = n.LineHeight.Value;
if ((diff & TextPropChanged.MaxLines) != 0) tb.MaxLines = n.MaxLines;
if ((diff & TextPropChanged.CharacterSpacing) != 0) tb.CharacterSpacing = n.CharacterSpacing;
if ((diff & TextPropChanged.TextDecorations) != 0) tb.TextDecorations = n.TextDecorations;
if ((diff & TextPropChanged.Setters) != 0) ApplySetters(n.Setters, tb);
return null;
}
private UIElement? UpdateRichTextBlock(RichTextBlockElement o, RichTextBlockElement n, WinUI.RichTextBlock rtb)
{
rtb.IsTextSelectionEnabled = n.IsTextSelectionEnabled;
if (n.FontSize.HasValue) rtb.FontSize = n.FontSize.Value;
if (n.TextWrapping.HasValue && rtb.TextWrapping != n.TextWrapping.Value) rtb.TextWrapping = n.TextWrapping.Value;
if (rtb.MaxLines != n.MaxLines) rtb.MaxLines = n.MaxLines;
if (n.LineHeight.HasValue && rtb.LineHeight != n.LineHeight.Value) rtb.LineHeight = n.LineHeight.Value;
if (n.TextAlignment.HasValue && rtb.TextAlignment != n.TextAlignment.Value) rtb.TextAlignment = n.TextAlignment.Value;
if (n.TextTrimming.HasValue && rtb.TextTrimming != n.TextTrimming.Value) rtb.TextTrimming = n.TextTrimming.Value;
if (rtb.CharacterSpacing != n.CharacterSpacing) rtb.CharacterSpacing = n.CharacterSpacing;
var oldParas = o.Paragraphs;
var newParas = n.Paragraphs;
// Both use simple text (no Paragraphs) — fast path.
if (oldParas is null && newParas is null)
{
if (o.Text != n.Text)
{
// Cache the WinRT collection reference to avoid repeated interop calls.
var blocks = rtb.Blocks;
if (blocks.Count > 0 &&
blocks[0] is Microsoft.UI.Xaml.Documents.Paragraph p0)
{
var inlines = p0.Inlines;
if (inlines.Count > 0 && inlines[0] is Microsoft.UI.Xaml.Documents.Run r0)
r0.Text = n.Text;
}
}
ApplySetters(n.Setters, rtb);
return null;
}
// Structural mismatch (one has Paragraphs, other doesn't) — full rebuild.
if (oldParas is null || newParas is null)
{
RebuildRichTextBlocks(n, rtb);
ApplySetters(n.Setters, rtb);
return null;
}
// Both have Paragraphs — diff incrementally.
int oldCount = oldParas.Length;
int newCount = newParas.Length;
int commonCount = Math.Min(oldCount, newCount);
// Cache the WinRT Blocks collection to avoid repeated interop calls.
var rtbBlocks = rtb.Blocks;
// Update existing paragraphs in place.
for (int pi = 0; pi < commonCount; pi++)
{
var oldPara = oldParas[pi];
var newPara = newParas[pi];
// Skip paragraphs whose content is structurally identical.
if (Element.ParagraphEqual(oldPara, newPara)) continue;
if (rtbBlocks.Count <= pi) break;
var winPara = (Microsoft.UI.Xaml.Documents.Paragraph)rtbBlocks[pi];
DiffParagraphInlines(oldPara, newPara, winPara);
}
// Remove excess paragraphs.
while (rtbBlocks.Count > newCount)
rtbBlocks.RemoveAt(rtbBlocks.Count - 1);
// Add new paragraphs.
for (int pi = oldCount; pi < newCount; pi++)
rtbBlocks.Add(MountParagraph(newParas[pi]));
ApplySetters(n.Setters, rtb);
return null;
}
private static void DiffParagraphInlines(RichTextParagraph oldPara, RichTextParagraph newPara,
Microsoft.UI.Xaml.Documents.Paragraph winPara)
{
var oldInlines = oldPara.Inlines;
var newInlines = newPara.Inlines;
int oldCount = oldInlines.Length;
int newCount = newInlines.Length;
int commonCount = Math.Min(oldCount, newCount);
// Cache the WinRT InlineCollection once — each .Inlines access is a managed→WinRT
// interop call, and each indexed get (winInlines[i]) is another. For documents with
// hundreds of inlines this was the dominant cost in the profile (~14% self CPU).
var winInlines = winPara.Inlines;
// Update existing inlines in place where types match.
for (int i = 0; i < commonCount; i++)
{
var oldInl = oldInlines[i];
var newInl = newInlines[i];
// Skip inlines that are record-equal (no changes).
if (oldInl == newInl) continue;
if (oldInl.GetType() != newInl.GetType())
{
// Type changed — replace this inline.
winInlines.RemoveAt(i);
winInlines.Insert(i, MountInline(newInl));
continue;
}
var winInline = winInlines[i];
switch (newInl)
{
case RichTextRun newRun:
if (winInline is Microsoft.UI.Xaml.Documents.Run winRun)
UpdateRun((RichTextRun)oldInl, newRun, winRun);
break;
case RichTextHyperlink newLink:
if (winInline is Microsoft.UI.Xaml.Documents.Hyperlink winHl)
UpdateHyperlink((RichTextHyperlink)oldInl, newLink, winHl);
break;
case RichTextLineBreak:
break;
}
}
// Remove excess inlines.
while (winInlines.Count > newCount)
winInlines.RemoveAt(winInlines.Count - 1);
// Add new inlines.
for (int i = oldCount; i < newCount; i++)
winInlines.Add(MountInline(newInlines[i]));
}
private static void UpdateRun(RichTextRun oldRun, RichTextRun newRun,
Microsoft.UI.Xaml.Documents.Run winRun)
{
if (oldRun.Text != newRun.Text)
winRun.Text = newRun.Text;
if (oldRun.IsBold != newRun.IsBold)
winRun.FontWeight = newRun.IsBold ? Microsoft.UI.Text.FontWeights.Bold : Microsoft.UI.Text.FontWeights.Normal;
if (oldRun.IsItalic != newRun.IsItalic)
winRun.FontStyle = newRun.IsItalic ? global::Windows.UI.Text.FontStyle.Italic : global::Windows.UI.Text.FontStyle.Normal;
if (oldRun.IsStrikethrough != newRun.IsStrikethrough)
winRun.TextDecorations = newRun.IsStrikethrough ? global::Windows.UI.Text.TextDecorations.Strikethrough : global::Windows.UI.Text.TextDecorations.None;
if (oldRun.FontSize != newRun.FontSize)
winRun.FontSize = newRun.FontSize ?? (double)Microsoft.UI.Xaml.DependencyProperty.UnsetValue;
if (oldRun.FontFamily != newRun.FontFamily)
{
if (newRun.FontFamily is not null)
winRun.FontFamily = WinRTCache.GetFontFamily(newRun.FontFamily);
else
winRun.ClearValue(Microsoft.UI.Xaml.Documents.TextElement.FontFamilyProperty);
}
if (!ReferenceEquals(oldRun.Foreground, newRun.Foreground))
winRun.Foreground = newRun.Foreground;
}
private static void UpdateHyperlink(RichTextHyperlink oldLink, RichTextHyperlink newLink,
Microsoft.UI.Xaml.Documents.Hyperlink winHl)
{
if (oldLink.NavigateUri != newLink.NavigateUri)
{
try { winHl.NavigateUri = newLink.NavigateUri; }
catch (Exception) { winHl.NavigateUri = new Uri("about:error"); }
}
if (oldLink.Text != newLink.Text && winHl.Inlines.Count > 0 &&
winHl.Inlines[0] is Microsoft.UI.Xaml.Documents.Run hlRun)
hlRun.Text = newLink.Text;
}
private static Microsoft.UI.Xaml.Documents.Inline MountInline(RichTextInline inline)
{
switch (inline)
{
case RichTextRun run:
var r = new Microsoft.UI.Xaml.Documents.Run { Text = run.Text };
if (run.IsBold) r.FontWeight = Microsoft.UI.Text.FontWeights.Bold;
if (run.IsItalic) r.FontStyle = global::Windows.UI.Text.FontStyle.Italic;
if (run.IsStrikethrough) r.TextDecorations = global::Windows.UI.Text.TextDecorations.Strikethrough;
if (run.FontSize.HasValue) r.FontSize = run.FontSize.Value;
if (run.FontFamily is not null) r.FontFamily = WinRTCache.GetFontFamily(run.FontFamily);
if (run.Foreground is not null) r.Foreground = run.Foreground;
return r;
case RichTextHyperlink link:
var l = link?.NavigateUri ?? new Uri("about:blank");
l = l.ToString().Length < 1 ? l = new Uri("about:blank") : l;
var hl = new Microsoft.UI.Xaml.Documents.Hyperlink();
try { hl.NavigateUri = l; } catch { hl.NavigateUri = new Uri("about:blank"); }
hl.Inlines.Add(new Microsoft.UI.Xaml.Documents.Run { Text = link?.Text ?? ""});
return hl;
case RichTextLineBreak:
return new Microsoft.UI.Xaml.Documents.LineBreak();
default:
return new Microsoft.UI.Xaml.Documents.Run { Text = "" };
}
}
private static Microsoft.UI.Xaml.Documents.Paragraph MountParagraph(RichTextParagraph para)
{
var p = new Microsoft.UI.Xaml.Documents.Paragraph();
foreach (var inline in para.Inlines)
p.Inlines.Add(MountInline(inline));
return p;
}
private static void RebuildRichTextBlocks(RichTextBlockElement n, WinUI.RichTextBlock rtb)
{
rtb.Blocks.Clear();
if (n.Paragraphs is not null)
{
foreach (var para in n.Paragraphs)
rtb.Blocks.Add(MountParagraph(para));
}
else
{
var p = new Microsoft.UI.Xaml.Documents.Paragraph();
p.Inlines.Add(new Microsoft.UI.Xaml.Documents.Run { Text = n.Text });
rtb.Blocks.Add(p);
}
}
private UIElement? UpdateButton(ButtonElement o, ButtonElement n, WinUI.Button b, Action requestRerender)
{
ApplyButtonEnabledState(b, n);
if (n.ContentElement is not null && o.ContentElement is not null && b.Content is UIElement existingContent)
{
var replacement = UpdateChild(o.ContentElement, n.ContentElement, existingContent, requestRerender);
if (replacement is not null)
{
UnmountChild(existingContent);
b.Content = replacement;
}
}
else if (n.ContentElement is not null)
{
if (b.Content is UIElement oldContent) UnmountChild(oldContent);
b.Content = Mount(n.ContentElement, requestRerender);
}
else
{
b.Content = n.Label;
}
SetElementTag(b, n);
EnsureButtonWiring(b, n);
ApplySetters(n.Setters, b);
return null;
}
private UIElement? UpdateHyperlinkButton(HyperlinkButtonElement o, HyperlinkButtonElement n, WinUI.HyperlinkButton hb)
{
hb.Content = n.Content;
// Unconditional: a transition to null must clear the stale navigation target.
if (o.NavigateUri != n.NavigateUri) hb.NavigateUri = n.NavigateUri;
SetElementTag(hb, n);
if (o.OnClick is null && n.OnClick is not null)
hb.Click += (s, _) => (GetElementTag((UIElement)s!) as HyperlinkButtonElement)?.OnClick?.Invoke();
ApplySetters(n.Setters, hb);
return null;
}
private UIElement? UpdateRepeatButton(RepeatButtonElement o, RepeatButtonElement n, WinPrim.RepeatButton rb)
{
rb.Content = n.Label; rb.Delay = n.Delay; rb.Interval = n.Interval; SetElementTag(rb, n);
if (o.OnClick is null && n.OnClick is not null)
rb.Click += (s, _) => (GetElementTag((UIElement)s!) as RepeatButtonElement)?.OnClick?.Invoke();
ApplySetters(n.Setters, rb);
return null;
}
private UIElement? UpdateToggleButton(ToggleButtonElement o, ToggleButtonElement n, WinPrim.ToggleButton tb)
{
tb.Content = n.Label;
if (n.IsThreeState)
{
if (!tb.IsThreeState) tb.IsThreeState = true;
if (tb.IsChecked != n.CheckedState) tb.IsChecked = n.CheckedState;
}
else
{
if (tb.IsThreeState) tb.IsThreeState = false;
if ((tb.IsChecked ?? false) != n.IsChecked) tb.IsChecked = n.IsChecked;
}
SetElementTag(tb, n);
bool oldWired = o.OnIsCheckedChanged is not null || o.OnCheckedStateChanged is not null;
bool newWired = n.OnIsCheckedChanged is not null || n.OnCheckedStateChanged is not null;
if (!oldWired && newWired)
tb.Click += (s, _) =>
{
var t = (WinPrim.ToggleButton)s!;
if (GetElementTag(t) is not ToggleButtonElement live) return;
live.OnIsCheckedChanged?.Invoke(t.IsChecked ?? false);
live.OnCheckedStateChanged?.Invoke(t.IsChecked);
};
ApplySetters(n.Setters, tb);
return null;
}
private UIElement? UpdateDropDownButton(DropDownButtonElement o, DropDownButtonElement n, WinUI.DropDownButton ddb, Action requestRerender)
{
if (ddb.Content as string != n.Label) ddb.Content = n.Label;
SetElementTag(ddb, n);
if (n.Flyout is not null)
ApplyFlyoutAttachment(ddb, o.Flyout, n.Flyout, requestRerender);
else if (o.Flyout is not null)
ddb.Flyout = null;
ApplySetters(n.Setters, ddb);
return null;
}
private UIElement? UpdateSplitButton(SplitButtonElement o, SplitButtonElement n, WinUI.SplitButton sb, Action requestRerender)
{
sb.Content = n.Label; SetElementTag(sb, n);
if (o.OnClick is null && n.OnClick is not null)
sb.Click += (s, _) => (GetElementTag((UIElement)s!) as SplitButtonElement)?.OnClick?.Invoke();
if (n.Flyout is not null)
ApplyFlyoutAttachment(sb, o.Flyout, n.Flyout, requestRerender);
else if (o.Flyout is not null)
sb.Flyout = null;
ApplySetters(n.Setters, sb);
return null;
}
private UIElement? UpdateToggleSplitButton(ToggleSplitButtonElement o, ToggleSplitButtonElement n, WinUI.ToggleSplitButton tsb, Action requestRerender)
{
SetElementTag(tsb, n);
if (o.OnIsCheckedChanged is null && n.OnIsCheckedChanged is not null)
tsb.IsCheckedChanged += (s, _) =>
{
var t = (WinUI.ToggleSplitButton)s!;
if (ChangeEchoSuppressor.ShouldSuppress(t)) return;
(GetElementTag(t) as ToggleSplitButtonElement)?.OnIsCheckedChanged?.Invoke(t.IsChecked);
};
tsb.Content = n.Label;
if (tsb.IsChecked != n.IsChecked)
{
ChangeEchoSuppressor.BeginSuppress(tsb);
tsb.IsChecked = n.IsChecked;
}
if (n.Flyout is not null)
ApplyFlyoutAttachment(tsb, o.Flyout, n.Flyout, requestRerender);
else if (o.Flyout is not null)
tsb.Flyout = null;
ApplySetters(n.Setters, tsb);
return null;
}
private UIElement? UpdateTextField(TextFieldElement o, TextFieldElement n, TextBox tb, Action requestRerender)
{
// Tag first so any echoed TextChanged sees this element.
SetElementTag(tb, n);
EnsureTextFieldWiring(tb, n, requestRerender);
if (o.Value != n.Value)
{
// Element value changed — always enforce
if (tb.Text != n.Value)
{
ChangeEchoSuppressor.BeginSuppress(tb);
tb.Text = n.Value;
}
}
else if (n.OnChanged is not null && tb.Text != n.Value)
{
// Controlled mode (onChange wired): snap back filtered/rejected input.
// The TextBox text diverges from the controlled value because the
// callback filtered it to the same state (e.g. digits-only rejecting alpha).
var caret = tb.SelectionStart;
ChangeEchoSuppressor.BeginSuppress(tb);
tb.Text = n.Value;
tb.SelectionStart = Math.Min(caret, tb.Text.Length);
}
else if (n.OnChanged is null && tb.Text != n.Value)
{
// Uncontrolled divergence: value is set but no onChange to reconcile.
// Log once per field to help developers catch mismatched bindings.
_logger?.LogWarning(
"TextField value diverged from controlled value with no OnChanged handler. " +
"Controlled: \"{ControlledValue}\", Actual: \"{ActualValue}\". " +
"Wire up OnChanged to keep state in sync, or this field won't reflect user edits after re-renders.",
Truncate(n.Value, 20), Truncate(tb.Text, 20));
}
tb.PlaceholderText = n.Placeholder ?? "";
if (n.Header is not null) tb.Header = n.Header;
if (n.IsReadOnly.HasValue) tb.IsReadOnly = n.IsReadOnly.Value;
if (n.AcceptsReturn.HasValue) tb.AcceptsReturn = n.AcceptsReturn.Value;
if (n.TextWrapping.HasValue) tb.TextWrapping = n.TextWrapping.Value;
if (tb.MaxLength != n.MaxLength) tb.MaxLength = n.MaxLength;
if (n.IsSpellCheckEnabled.HasValue && tb.IsSpellCheckEnabled != n.IsSpellCheckEnabled.Value)
tb.IsSpellCheckEnabled = n.IsSpellCheckEnabled.Value;
if (tb.CharacterCasing != n.CharacterCasing) tb.CharacterCasing = n.CharacterCasing;
if (tb.TextAlignment != n.TextAlignment) tb.TextAlignment = n.TextAlignment;
if (n.Description is not null) tb.Description = n.Description;
// Apply selection position after text — must come after Text is set so the range is valid
if (n.SelectionStart.HasValue) tb.SelectionStart = Math.Min(n.SelectionStart.Value, tb.Text.Length);
if (n.SelectionLength.HasValue) tb.SelectionLength = Math.Min(n.SelectionLength.Value, tb.Text.Length - tb.SelectionStart);
ApplySetters(n.Setters, tb);
return null;
}
private UIElement? UpdatePasswordBox(PasswordBoxElement o, PasswordBoxElement n, WinUI.PasswordBox pb)
{
SetElementTag(pb, n);
if (o.OnPasswordChanged is null && n.OnPasswordChanged is not null)
pb.PasswordChanged += (s, _) =>
{
var c = (UIElement)s!;
if (ChangeEchoSuppressor.ShouldSuppress(c)) return;
(GetElementTag(c) as PasswordBoxElement)?.OnPasswordChanged?.Invoke(((WinUI.PasswordBox)c).Password);
};
if (pb.Password != n.Password)
{
ChangeEchoSuppressor.BeginSuppress(pb);
pb.Password = n.Password;
}
pb.PlaceholderText = n.PlaceholderText ?? "";
if (n.Header is not null) pb.Header = n.Header;
if (pb.MaxLength != n.MaxLength) pb.MaxLength = n.MaxLength;
if (pb.PasswordRevealMode != n.PasswordRevealMode) pb.PasswordRevealMode = n.PasswordRevealMode;
if (n.PasswordChar is not null && pb.PasswordChar != n.PasswordChar) pb.PasswordChar = n.PasswordChar;
ApplySetters(n.Setters, pb);
return null;
}
private UIElement? UpdateNumberBox(NumberBoxElement o, NumberBoxElement n, WinUI.NumberBox nb)
{
SetElementTag(nb, n);
if (o.OnValueChanged is null && n.OnValueChanged is not null)
nb.ValueChanged += (s, _) =>
{
var box = (WinUI.NumberBox)s!;
if (ChangeEchoSuppressor.ShouldSuppress(box)) return;
(GetElementTag(box) as NumberBoxElement)?.OnValueChanged?.Invoke(box.Value);
};
// Set Min/Max before Value so a new, in-range Value doesn't get
// coerced by a stale range. But Min/Max writes can themselves coerce
// the existing Value, which raises ValueChanged — suppress those
// echoes too, one token per write that might fire.
if (nb.Minimum != n.Minimum)
{
if (nb.Value < n.Minimum) ChangeEchoSuppressor.BeginSuppress(nb);
nb.Minimum = n.Minimum;
}
if (nb.Maximum != n.Maximum)
{
if (nb.Value > n.Maximum) ChangeEchoSuppressor.BeginSuppress(nb);
nb.Maximum = n.Maximum;
}
if (nb.Value != n.Value)
{
// Immediate mode: if the user's current text already represents
// n.Value, leave the text alone — writing Value mid-edit would
// reformat the text and clobber the caret / trailing zeros /
// partial decimals while the user is still typing.
var skipValueWrite = n.GetAttached<Microsoft.UI.Reactor.Controls.Validation.ImmediateValueAttached>() is not null
&& double.TryParse(nb.Text,
global::System.Globalization.NumberStyles.Float,
global::System.Globalization.CultureInfo.CurrentCulture, out var typed)
&& double.IsFinite(typed) // NaN/Infinity must never defeat the skip and slip through
&& typed == n.Value;
if (!skipValueWrite)
{
ChangeEchoSuppressor.BeginSuppress(nb);
nb.Value = n.Value;
}
}
nb.SmallChange = n.SmallChange; nb.LargeChange = n.LargeChange;
nb.SpinButtonPlacementMode = n.SpinButtonPlacement;
if (nb.AcceptsExpression != n.AcceptsExpression) nb.AcceptsExpression = n.AcceptsExpression;
if (nb.ValidationMode != n.ValidationMode) nb.ValidationMode = n.ValidationMode;
// NumberFormatter is reference-equality — only re-assign when the
// record swap actually changed the formatter, so a same-formatter
// re-render doesn't reformat the text (and break in-progress edits).
if (!ReferenceEquals(o.NumberFormatter, n.NumberFormatter) && n.NumberFormatter is not null)
nb.NumberFormatter = n.NumberFormatter;
if (n.Description is not null) nb.Description = n.Description;
if (n.Header is not null) nb.Header = n.Header;
ApplySetters(n.Setters, nb);
return null;
}
private UIElement? UpdateAutoSuggestBox(AutoSuggestBoxElement o, AutoSuggestBoxElement n, WinUI.AutoSuggestBox asb)
{
// AutoSuggestBox already filters TextChanged to UserInput only, so
// programmatic Text= is already safe. Suppress anyway for consistency
// with the other editors (covers future handler changes).
SetElementTag(asb, n);
if (o.OnTextChanged is null && n.OnTextChanged is not null)
asb.TextChanged += (s, args) =>
{
if (args.Reason == WinUI.AutoSuggestionBoxTextChangeReason.UserInput)
(GetElementTag((UIElement)s!) as AutoSuggestBoxElement)?.OnTextChanged?.Invoke(((WinUI.AutoSuggestBox)s!).Text);
};
if (o.OnQuerySubmitted is null && n.OnQuerySubmitted is not null)
asb.QuerySubmitted += (s, args) =>
(GetElementTag((UIElement)s!) as AutoSuggestBoxElement)?.OnQuerySubmitted?.Invoke(args.QueryText);
if (o.OnSuggestionChosen is null && n.OnSuggestionChosen is not null)
asb.SuggestionChosen += (s, args) =>
(GetElementTag((UIElement)s!) as AutoSuggestBoxElement)?.OnSuggestionChosen?.Invoke(args.SelectedItem?.ToString() ?? "");
if (asb.Text != n.Text)
{
ChangeEchoSuppressor.BeginSuppress(asb);
asb.Text = n.Text;
}
asb.PlaceholderText = n.PlaceholderText ?? "";
if (n.Suggestions.Length > 0) asb.ItemsSource = n.Suggestions;
if (n.Header is not null) asb.Header = n.Header;
if (!ReferenceEquals(o.QueryIcon, n.QueryIcon) && n.QueryIcon is not null)
asb.QueryIcon = ResolveIcon(n.QueryIcon, null);
if (asb.IsSuggestionListOpen != n.IsSuggestionListOpen) asb.IsSuggestionListOpen = n.IsSuggestionListOpen;
ApplySetters(n.Setters, asb);
return null;
}
private UIElement? UpdateCheckBox(CheckBoxElement o, CheckBoxElement n, WinUI.CheckBox cb)
{
SetElementTag(cb, n);
bool oldWired = o.OnIsCheckedChanged is not null || o.OnCheckedStateChanged is not null;
bool newWired = n.OnIsCheckedChanged is not null || n.OnCheckedStateChanged is not null;
if (!oldWired && newWired)
{
cb.Checked += (s, _) =>
{
var c = (UIElement)s!;
if (ChangeEchoSuppressor.ShouldSuppress(c)) return;
var el = GetElementTag(c) as CheckBoxElement;
el?.OnIsCheckedChanged?.Invoke(true);
el?.OnCheckedStateChanged?.Invoke(true);
};
cb.Unchecked += (s, _) =>
{
var c = (UIElement)s!;
if (ChangeEchoSuppressor.ShouldSuppress(c)) return;
var el = GetElementTag(c) as CheckBoxElement;
el?.OnIsCheckedChanged?.Invoke(false);
el?.OnCheckedStateChanged?.Invoke(false);
};
cb.Indeterminate += (s, _) =>
{
var c = (UIElement)s!;
if (ChangeEchoSuppressor.ShouldSuppress(c)) return;
var el = GetElementTag(c) as CheckBoxElement;
el?.OnCheckedStateChanged?.Invoke(null);
};
}
cb.Content = n.Label;
cb.IsThreeState = n.IsThreeState;
var target = n.IsThreeState ? n.CheckedState : n.IsChecked;
if (cb.IsChecked != target)
{
ChangeEchoSuppressor.BeginSuppress(cb);
cb.IsChecked = target;
}
ApplySetters(n.Setters, cb);
return null;
}
private UIElement? UpdateRadioButton(RadioButtonElement o, RadioButtonElement n, WinUI.RadioButton rb)
{
SetElementTag(rb, n);
if (o.OnIsCheckedChanged is null && n.OnIsCheckedChanged is not null)