-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathReconciler.Mount.cs
More file actions
3973 lines (3650 loc) · 179 KB
/
Reconciler.Mount.cs
File metadata and controls
3973 lines (3650 loc) · 179 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.Hooks;
using Microsoft.UI.Reactor.Hosting;
using Microsoft.UI.Reactor.Controls.Validation;
using Validation = Microsoft.UI.Reactor.Controls.Validation;
using Microsoft.Extensions.Logging;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
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;
namespace Microsoft.UI.Reactor.Core;
// AI-HINT: Reconciler.Mount.cs — creates real WinUI controls from Element descriptions.
// Mount() is a big switch over all Element subtypes → MountXxx() methods.
// Each MountXxx allocates (or rents from pool) a WinUI control, sets properties,
// wires event handlers that look up the current Element via the ReactorAttached
// DP (see Reconciler.SetElementTag), so handlers are wired once and survive
// element recycling — the trampoline re-reads the current Element on each fire.
// Context values are pushed/popped around child processing.
public sealed partial class Reconciler
{
/// <summary>
/// Creates a WinUI control tree from an Element tree. Returns null for EmptyElement.
/// </summary>
// <snippet:mount-phase>
public UIElement? Mount(Element element, Action requestRerender)
{
// Unwrap legacy ModifiedElement (backward compat)
ElementModifiers? modifiers = element.Modifiers;
if (element is ModifiedElement mod)
{
modifiers = mod.WrappedModifiers;
if (mod.Inner.Modifiers is not null)
modifiers = modifiers.Merge(mod.Inner.Modifiers);
element = mod.Inner;
}
// </snippet:mount-phase>
// Push context values onto scope before processing children
var ctxValues = element.ContextValues;
int ctxCount = 0;
if (ctxValues is { Count: > 0 })
{
_contextScope.Push(ctxValues);
ctxCount = ctxValues.Count;
}
UIElement? control;
// Push stagger scope if this element has StaggerConfig — children mounted
// inside MountXxx will consume stagger indices for their enter transitions.
bool pushedStagger = element.StaggerConfig is not null;
if (pushedStagger)
PushStaggerScope(element.StaggerConfig!.Delay);
try
{
// Spec 047 §14 Phase 1 (1.1) — V1 handler registry dispatch.
// When the feature flag is ON, ported built-in handlers in
// `_v1Handlers` win before the external `_typeRegistry`. When the
// flag is OFF, this step is skipped entirely and ported controls
// fall through to the legacy MountXxx switch.
if (UseV1Protocol && _v1Handlers.TryGet(element.GetType(), out var v1Entry))
{
control = v1Entry.Mount(element, requestRerender, this);
}
// Registered types checked first
else if (_typeRegistry.TryGetValue(element.GetType(), out var reg))
{
control = reg.Mount(element, requestRerender, this);
}
else
{
control = element switch
{
TextBlockElement text => MountText(text),
RichTextBlockElement richText => MountRichTextBlock(richText),
ButtonElement btn => MountButton(btn, requestRerender),
HyperlinkButtonElement hlBtn => MountHyperlinkButton(hlBtn),
RepeatButtonElement repBtn => MountRepeatButton(repBtn),
ToggleButtonElement togBtn => MountToggleButton(togBtn),
DropDownButtonElement ddBtn => MountDropDownButton(ddBtn, requestRerender),
SplitButtonElement spBtn => MountSplitButton(spBtn, requestRerender),
ToggleSplitButtonElement tspBtn => MountToggleSplitButton(tspBtn, requestRerender),
RichEditBoxElement reb => MountRichEditBox(reb),
TextBoxElement textBoxElement => MountTextBox(textBoxElement, requestRerender),
PasswordBoxElement pw => MountPasswordBox(pw),
NumberBoxElement nb => MountNumberBox(nb),
AutoSuggestBoxElement asb => MountAutoSuggestBox(asb),
CheckBoxElement cb => MountCheckBox(cb),
RadioButtonElement rb => MountRadioButton(rb),
RadioButtonsElement rbs => MountRadioButtons(rbs),
ComboBoxElement combo => MountComboBox(combo, requestRerender),
SliderElement sl => MountSlider(sl),
ToggleSwitchElement ts => MountToggleSwitch(ts),
RatingControlElement rc => MountRatingControl(rc),
ColorPickerElement cp => MountColorPicker(cp),
CalendarDatePickerElement cdp => MountCalendarDatePicker(cdp),
DatePickerElement dp => MountDatePicker(dp),
TimePickerElement tp => MountTimePicker(tp),
ProgressElement prog => MountProgress(prog),
ProgressRingElement ring => MountProgressRing(ring),
ImageElement img => MountImage(img),
PersonPictureElement pp => MountPersonPicture(pp),
WebView2Element wv => MountWebView2(wv),
WrapGridElement wg => MountWrapGrid(wg, requestRerender),
StackElement stack => MountStack(stack, requestRerender),
GridElement grid => MountGrid(grid, requestRerender),
ScrollViewerElement scroll => MountScrollViewer(scroll, requestRerender),
ScrollViewElement scroll => MountScrollView(scroll, requestRerender),
BorderElement border => MountBorder(border, requestRerender),
ExpanderElement exp => MountExpander(exp, requestRerender),
SplitViewElement sv => MountSplitView(sv, requestRerender),
ViewboxElement vb => MountViewbox(vb, requestRerender),
CanvasElement cvs => MountCanvas(cvs, requestRerender),
FlexElement flex => MountFlex(flex, requestRerender),
NavigationHostElement navHost => MountNavigationHost(navHost, requestRerender),
NavigationViewElement nav => MountNavigationView(nav, requestRerender),
TitleBarElement tb => MountTitleBar(tb, requestRerender),
TabViewElement tab => MountTabView(tab, requestRerender),
BreadcrumbBarElement bcb => MountBreadcrumbBar(bcb),
PivotElement pvt => MountPivot(pvt, requestRerender),
ListViewElement lv => MountListView(lv, requestRerender),
GridViewElement gv => MountGridView(gv, requestRerender),
TreeViewElement tv => MountTreeView(tv, requestRerender),
FlipViewElement fv => MountFlipView(fv, requestRerender),
InfoBarElement ib => MountInfoBar(ib, requestRerender),
InfoBadgeElement badge => MountInfoBadge(badge),
ContentDialogElement cdEl => MountContentDialog(cdEl, requestRerender),
FlyoutElement flyEl => MountFlyout(flyEl, requestRerender),
TeachingTipElement ttEl => MountTeachingTip(ttEl, requestRerender),
MenuBarElement mbEl => MountMenuBar(mbEl),
CommandBarElement cmdEl => MountCommandBar(cmdEl, requestRerender),
MenuFlyoutElement mfEl => MountMenuFlyout(mfEl, requestRerender),
TemplatedListElementBase tl => MountTemplatedList(tl, requestRerender),
LazyStackElementBase lazy => MountLazyStack(lazy, requestRerender),
ItemsRepeaterElementBase ir => MountItemsRepeater(ir, requestRerender),
ItemsViewElementBase iv => MountItemsView(iv, requestRerender),
ItemContainerElement ic => MountItemContainer(ic, requestRerender),
RectangleElement rect => MountRectangle(rect),
EllipseElement ell => MountEllipse(ell),
LineElement ln => MountLine(ln),
PathElement pa => MountPath(pa),
RelativePanelElement rp => MountRelativePanel(rp, requestRerender),
MediaPlayerElementElement mpe => MountMediaPlayerElement(mpe),
AnimatedVisualPlayerElement avp => MountAnimatedVisualPlayer(avp),
SemanticZoomElement sz => MountSemanticZoom(sz, requestRerender),
ListBoxElement lb => MountListBox(lb),
SelectorBarElement sb => MountSelectorBar(sb),
PipsPagerElement pp => MountPipsPager(pp),
AnnotatedScrollBarElement asb => MountAnnotatedScrollBar(asb),
PopupElement popup => MountPopup(popup, requestRerender),
RefreshContainerElement rc => MountRefreshContainer(rc, requestRerender),
CommandBarFlyoutElement cbf => MountCommandBarFlyout(cbf, requestRerender),
CalendarViewElement cv => MountCalendarView(cv),
SwipeControlElement swipe => MountSwipeControl(swipe, requestRerender),
AnimatedIconElement ai => MountAnimatedIcon(ai),
IconElement ie => MountIcon(ie),
ParallaxViewElement pv => MountParallaxView(pv, requestRerender),
MapControlElement mc => MountMapControl(mc),
FrameElement frame => MountFrame(frame),
CommandHostElement ch => MountCommandHost(ch, requestRerender),
ErrorBoundaryElement eb => MountErrorBoundary(eb, requestRerender),
Validation.FormFieldElement ff => MountFormField(ff, requestRerender),
Validation.ValidationVisualizerElement vv => MountValidationVisualizer(vv, requestRerender),
Validation.ValidationRuleElement rule => MountValidationRule(rule),
SemanticElement sem => MountSemantic(sem, requestRerender),
AnnounceRegionElement ann => MountAnnounceRegion(ann),
XamlHostElement host => MountXamlHost(host),
XamlPageElement page => MountXamlPage(page),
ComponentElement comp => MountComponent(comp, requestRerender),
FuncElement func => MountFuncComponent(func, requestRerender),
MemoElement memo => MountMemoComponent(memo, requestRerender),
_ => null,
};
}
if (control is not null)
{
DebugUIElementsCreated++;
// Highlight capture is gated by the flag, not just by list
// existence: the list is allocated lazily on first flag-on and
// never freed afterward, so a non-null check would keep
// appending forever once the user toggles the flag off.
if (ReactorFeatureFlags.HighlightReconcileChanges
&& _highlightMounted is not null)
_highlightMounted.Add(control);
}
// Apply inline modifiers after mounting
if (modifiers is not null && control is FrameworkElement fe)
ApplyModifiers(fe, modifiers, requestRerender);
// After modifiers + setters have had a chance to set an explicit
// AutomationName, fall back to the control's visible caption so UIA
// clients that read AutomationProperties.Name directly don't see an
// empty string on a Button("Save", …). Author-supplied names win.
if (control is FrameworkElement captionFe)
ApplyDefaultAutomationName(captionFe, ResolveCaptionForElement(element));
// Apply theme-resource bindings (ThemeRef → resolved Brush from WinUI resources)
if (element.ThemeBindings is not null && control is FrameworkElement thFe)
ApplyThemeBindings(thFe, element.ThemeBindings);
// Apply per-control resource overrides (lightweight styling)
if (element.ResourceOverrides is not null && control is FrameworkElement resFe)
ApplyResourceOverrides(resFe, null, element.ResourceOverrides);
// Apply transitions after mounting (runs after .Set() callbacks)
if (control is not null && (element.ImplicitTransitions is not null || element.ThemeTransitions is not null))
ApplyTransitions(control, element.ImplicitTransitions, element.ThemeTransitions);
// Apply Composition-layer layout animation (implicit Offset/Size animation on Visual)
if (control is not null && element.LayoutAnimation is not null)
ApplyLayoutAnimation(control, element.LayoutAnimation);
// Apply compositor property animation (.Animate() modifier)
if (control is not null && element.AnimationConfig is not null)
ApplyPropertyAnimation(control, element.AnimationConfig, element.LayoutAnimation);
// Apply enter transition (.Transition() modifier)
if (control is not null && element.ElementTransition is not null)
{
var (staggerIdx, staggerDly) = ConsumeStaggerIndex();
ApplyEnterTransition(control, element.ElementTransition, staggerIdx, staggerDly);
}
// Apply interaction states (.InteractionStates() modifier)
if (control is not null && element.InteractionStates is not null)
ApplyInteractionStates(control, element.InteractionStates);
// Apply keyframe animations (.Keyframes() modifier)
if (control is not null && element.KeyframeAnimations is not null)
ApplyKeyframeAnimations(control, element.KeyframeAnimations);
// Apply scroll-linked expression animations (.ScrollLinked() modifier)
if (control is not null && element.ScrollAnimation is not null)
ApplyScrollAnimation(control, element.ScrollAnimation);
// Apply stagger delays to children (.Stagger() modifier)
if (control is not null && element.StaggerConfig is not null)
ApplyStaggerDelays(control, element.StaggerConfig);
// Queue connected animation start if a prepared animation exists with this key
if (control is not null && element.ConnectedAnimationKey is not null)
QueueConnectedAnimationStart(control, element.ConnectedAnimationKey);
}
finally
{
if (pushedStagger)
PopStaggerScope();
if (ctxCount > 0)
_contextScope.Pop(ctxCount);
}
return control;
}
private TextBlock MountText(TextBlockElement text)
{
var tb = _pool.TryRent(typeof(TextBlock)) as TextBlock ?? new TextBlock();
tb.Text = text.Content;
if (text.FontSize.HasValue) tb.FontSize = text.FontSize.Value;
if (text.Weight.HasValue) tb.FontWeight = text.Weight.Value;
if (text.FontStyle.HasValue) tb.FontStyle = text.FontStyle.Value;
if (text.HorizontalAlignment.HasValue) tb.HorizontalAlignment = text.HorizontalAlignment.Value;
if (text.TextWrapping.HasValue) tb.TextWrapping = text.TextWrapping.Value;
if (text.TextAlignment.HasValue) tb.TextAlignment = text.TextAlignment.Value;
if (text.TextTrimming.HasValue) tb.TextTrimming = text.TextTrimming.Value;
if (text.IsTextSelectionEnabled.HasValue) tb.IsTextSelectionEnabled = text.IsTextSelectionEnabled.Value;
if (text.FontFamily is not null) tb.FontFamily = text.FontFamily;
if (text.LineHeight.HasValue) tb.LineHeight = text.LineHeight.Value;
if (text.MaxLines > 0) tb.MaxLines = text.MaxLines;
if (text.CharacterSpacing != 0) tb.CharacterSpacing = text.CharacterSpacing;
if (text.TextDecorations != global::Windows.UI.Text.TextDecorations.None) tb.TextDecorations = text.TextDecorations;
ApplySetters(text.Setters, tb);
return tb;
}
private WinUI.RichTextBlock MountRichTextBlock(RichTextBlockElement richText)
{
var rtb = _pool.TryRent(typeof(WinUI.RichTextBlock)) as WinUI.RichTextBlock ?? new WinUI.RichTextBlock();
rtb.IsTextSelectionEnabled = richText.IsTextSelectionEnabled;
if (richText.TextWrapping.HasValue) rtb.TextWrapping = richText.TextWrapping.Value;
// Shared helper with the V1 descriptor — clears Blocks then rebuilds
// from Paragraphs or falls back to a single Run with .Text. Extracted
// (Phase 3-final Batch B) so RichTextBlockDescriptor's .OneWay set
// lambda can call the same code path.
RebuildRichTextBlocks(richText, rtb);
if (richText.FontSize.HasValue) rtb.FontSize = richText.FontSize.Value;
if (richText.MaxLines > 0) rtb.MaxLines = richText.MaxLines;
if (richText.LineHeight.HasValue) rtb.LineHeight = richText.LineHeight.Value;
if (richText.TextAlignment.HasValue) rtb.TextAlignment = richText.TextAlignment.Value;
if (richText.TextTrimming.HasValue) rtb.TextTrimming = richText.TextTrimming.Value;
if (richText.CharacterSpacing != 0) rtb.CharacterSpacing = richText.CharacterSpacing;
ApplySetters(richText.Setters, rtb);
return rtb;
}
internal WinUI.Button MountButton(ButtonElement btn, Action requestRerender)
{
var rented = _pool.TryRent(typeof(WinUI.Button));
var button = rented as WinUI.Button ?? new WinUI.Button();
ApplyButtonEnabledState(button, btn);
if (btn.ContentElement is not null)
button.Content = Mount(btn.ContentElement, requestRerender);
else
button.Content = btn.Label;
SetElementTag(button, btn);
EnsureButtonWiring(button, btn);
ApplySetters(btn.Setters, button);
return button;
}
/// <summary>
/// Applies the (Disabled, DisabledFocusable) state to a WinUI Button.
/// True disable: IsEnabled=false (removes from tab order). Disabled-
/// focusable: IsEnabled=true plus visual dim; UIA still reports the
/// button as enabled (full AT "unavailable" reporting is a follow-up
/// requiring a custom AutomationPeer override). The Click trampoline
/// (see EnsureButtonWiring) drops invokes when the element is in
/// disabled-focusable mode.
/// </summary>
internal static void ApplyButtonEnabledState(WinUI.Button button, ButtonElement btn)
{
// Visual dim + Click trampoline drop. UIA still reports the button as
// enabled — a future fix would attach a custom ButtonAutomationPeer
// overriding IsEnabledCore() to fully mirror the WinUI Win32 / ARIA
// aria-disabled pattern. Tracked as a TODO; not required for the
// keyboard-reachability win this method delivers.
if (btn.IsDisabledFocusable)
{
button.IsEnabled = true;
button.Opacity = 0.4;
}
else
{
button.IsEnabled = btn.IsEnabled;
// ClearValue (not Opacity=1.0) so any opacity coming from a XAML
// style, template, or external code path survives. Forcing 1.0
// here would silently override a Setters/Resources Opacity binding
// every time the button rerenders out of disabled-focusable mode.
button.ClearValue(UIElement.OpacityProperty);
}
}
/// <summary>
/// Wires Button.Click trampoline only when the element has a handler AND
/// the control hasn't been wired yet. Dedupe key is the EventHandlerState
/// trampoline reference, attached on ReactorAttached.StateProperty (native
/// DO identity), so two managed RCWs over the same native Button share one
/// trampoline. Survives pool round-trips for the same reason.
/// </summary>
internal static void EnsureButtonWiring(WinUI.Button button, ButtonElement btn)
{
if (btn.OnClick is null) return;
var state = GetOrCreateEventState(button);
if (state.ButtonClickTrampoline is not null) return;
state.ButtonClickTrampoline = (s, _) =>
{
if (GetElementTag((UIElement)s!) is ButtonElement live)
{
if (live.IsDisabledFocusable) return;
live.OnClick?.Invoke();
}
};
button.Click += state.ButtonClickTrampoline;
}
private WinUI.HyperlinkButton MountHyperlinkButton(HyperlinkButtonElement hlBtn)
{
var hb = new WinUI.HyperlinkButton { Content = hlBtn.Content };
if (hlBtn.NavigateUri is not null) hb.NavigateUri = hlBtn.NavigateUri;
SetElementTag(hb, hlBtn);
if (hlBtn.OnClick is not null)
hb.Click += (s, _) => (GetElementTag((UIElement)s!) as HyperlinkButtonElement)?.OnClick?.Invoke();
ApplySetters(hlBtn.Setters, hb);
return hb;
}
private WinPrim.RepeatButton MountRepeatButton(RepeatButtonElement repBtn)
{
var rb = new WinPrim.RepeatButton { Content = repBtn.Label, Delay = repBtn.Delay, Interval = repBtn.Interval };
SetElementTag(rb, repBtn);
if (repBtn.OnClick is not null)
rb.Click += (s, _) => (GetElementTag((UIElement)s!) as RepeatButtonElement)?.OnClick?.Invoke();
ApplySetters(repBtn.Setters, rb);
return rb;
}
private WinPrim.ToggleButton MountToggleButton(ToggleButtonElement togBtn)
{
var tb = new WinPrim.ToggleButton { Content = togBtn.Label };
if (togBtn.IsThreeState)
{
tb.IsThreeState = true;
tb.IsChecked = togBtn.CheckedState;
}
else
{
tb.IsChecked = togBtn.IsChecked;
}
SetElementTag(tb, togBtn);
// Bind to Click — fires only for real user toggles. Checked/Unchecked
// would also fire when UpdateToggleButton rewrites IsChecked during a
// state-driven rerender, which would re-enter the callback and loop.
if (togBtn.OnIsCheckedChanged is not null || togBtn.OnCheckedStateChanged is not null)
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(togBtn.Setters, tb);
return tb;
}
private WinUI.DropDownButton MountDropDownButton(DropDownButtonElement ddBtn, Action requestRerender)
{
var ddb = new WinUI.DropDownButton { Content = ddBtn.Label };
if (ddBtn.Flyout is not null)
ddb.Flyout = CreateFlyoutFromElement(ddBtn.Flyout, requestRerender);
ApplySetters(ddBtn.Setters, ddb);
return ddb;
}
private WinUI.SplitButton MountSplitButton(SplitButtonElement spBtn, Action requestRerender)
{
var sb = new WinUI.SplitButton { Content = spBtn.Label };
SetElementTag(sb, spBtn);
if (spBtn.OnClick is not null)
sb.Click += (s, _) => (GetElementTag((UIElement)s!) as SplitButtonElement)?.OnClick?.Invoke();
if (spBtn.Flyout is not null)
sb.Flyout = CreateFlyoutFromElement(spBtn.Flyout, requestRerender);
ApplySetters(spBtn.Setters, sb);
return sb;
}
private WinUI.ToggleSplitButton MountToggleSplitButton(ToggleSplitButtonElement tspBtn, Action requestRerender)
{
var tsb = new WinUI.ToggleSplitButton { Content = tspBtn.Label, IsChecked = tspBtn.IsChecked };
SetElementTag(tsb, tspBtn);
if (tspBtn.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);
};
if (tspBtn.Flyout is not null)
tsb.Flyout = CreateFlyoutFromElement(tspBtn.Flyout, requestRerender);
ApplySetters(tspBtn.Setters, tsb);
return tsb;
}
private TextBox MountTextBox(TextBoxElement textBoxElement, Action requestRerender)
{
var rented = _pool.TryRent(typeof(TextBox));
var textBox = rented as TextBox ?? new TextBox();
// SetElementTag BEFORE writing Text: pooled controls retain their
// previous tag, and programmatic Text= fires TextChanged on the pooled
// event handler. Setting the new tag first ensures the handler reads
// this mount's element, not the pool's last owner. The BeginSuppress
// guard below is additional belt-and-suspenders against echo.
SetElementTag(textBox, textBoxElement);
// AcceptsReturn and TextWrapping must be set BEFORE Text. WinUI TextBox
// defaults to single-line mode (AcceptsReturn=false); assigning Text
// with embedded \r\n while in single-line mode silently strips the
// newlines, keeping only the first paragraph. Setting these first
// ensures multi-line content round-trips correctly on mount.
if (textBoxElement.AcceptsReturn == true) textBox.AcceptsReturn = true;
if (textBoxElement.TextWrapping.HasValue) textBox.TextWrapping = textBoxElement.TextWrapping.Value;
if (rented is not null && textBox.Text != textBoxElement.Value)
ChangeEchoSuppressor.BeginSuppress(textBox);
textBox.Text = textBoxElement.Value;
textBox.PlaceholderText = textBoxElement.PlaceholderText ?? "";
if (textBoxElement.Header is not null) textBox.Header = textBoxElement.Header;
if (textBoxElement.IsReadOnly == true) textBox.IsReadOnly = true;
if (textBoxElement.SelectionStart.HasValue) textBox.SelectionStart = textBoxElement.SelectionStart.Value;
if (textBoxElement.SelectionLength.HasValue) textBox.SelectionLength = textBoxElement.SelectionLength.Value;
if (textBoxElement.MaxLength != 0) textBox.MaxLength = textBoxElement.MaxLength;
if (textBoxElement.IsSpellCheckEnabled.HasValue) textBox.IsSpellCheckEnabled = textBoxElement.IsSpellCheckEnabled.Value;
if (textBoxElement.CharacterCasing != CharacterCasing.Normal) textBox.CharacterCasing = textBoxElement.CharacterCasing;
if (textBoxElement.TextAlignment != TextAlignment.Left) textBox.TextAlignment = textBoxElement.TextAlignment;
if (textBoxElement.Description is not null) textBox.Description = textBoxElement.Description;
EnsureTextBoxWiring(textBox, textBoxElement, requestRerender);
ApplySetters(textBoxElement.Setters, textBox);
return textBox;
}
/// <summary>
/// Wires TextBox's TextChanged/SelectionChanged trampolines only when the
/// element has a corresponding handler AND the control hasn't been wired
/// yet. Called from both Mount (fresh or pooled) and Update (null→non-null
/// transition). Dedupe through EventHandlerState (native-DO-keyed) so
/// pool round-trips and RCW projection both share one trampoline.
/// </summary>
internal static void EnsureTextBoxWiring(TextBox textBox, TextBoxElement textBoxElement, Action requestRerender)
{
if (textBoxElement.OnChanged is null && textBoxElement.OnSelectionChanged is null) return;
var state = GetOrCreateEventState(textBox);
if (textBoxElement.OnChanged is not null && state.TextBoxTextChangedTrampoline is null)
{
state.TextBoxTextChangedTrampoline = (_, _) =>
{
if (ChangeEchoSuppressor.ShouldSuppress(textBox)) return;
var tag = GetElementTag(textBox) as TextBoxElement;
tag?.OnChanged?.Invoke(textBox.Text);
// Controlled input: when onChange is wired, always request a
// re-render so UpdateTextBox can enforce the controlled value.
// Coalesces with any setState re-render (CAS gate).
// Without onChange the field is uncontrolled — no snap-back.
if (tag?.OnChanged is not null)
requestRerender();
};
textBox.TextChanged += state.TextBoxTextChangedTrampoline;
}
if (textBoxElement.OnSelectionChanged is not null && state.TextBoxSelectionChangedTrampoline is null)
{
state.TextBoxSelectionChangedTrampoline = (_, _) =>
(GetElementTag(textBox) as TextBoxElement)?.OnSelectionChanged?.Invoke(
textBox.SelectedText, textBox.SelectionStart, textBox.SelectionLength);
textBox.SelectionChanged += state.TextBoxSelectionChangedTrampoline;
}
}
private WinUI.PasswordBox MountPasswordBox(PasswordBoxElement pw)
{
var pb = new WinUI.PasswordBox
{
Password = pw.Password,
PlaceholderText = pw.PlaceholderText ?? "",
PasswordRevealMode = pw.PasswordRevealMode,
};
if (pw.Header is not null) pb.Header = pw.Header;
if (pw.MaxLength != 0) pb.MaxLength = pw.MaxLength;
if (pw.PasswordChar is not null) pb.PasswordChar = pw.PasswordChar;
SetElementTag(pb, pw);
if (pw.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);
};
ApplySetters(pw.Setters, pb);
return pb;
}
private WinUI.NumberBox MountNumberBox(NumberBoxElement nb)
{
var numBox = new WinUI.NumberBox
{
Value = nb.Value, Minimum = nb.Minimum, Maximum = nb.Maximum,
SmallChange = nb.SmallChange, LargeChange = nb.LargeChange,
PlaceholderText = nb.PlaceholderText ?? "",
SpinButtonPlacementMode = nb.SpinButtonPlacement,
AcceptsExpression = nb.AcceptsExpression,
ValidationMode = nb.ValidationMode,
};
if (nb.NumberFormatter is not null) numBox.NumberFormatter = nb.NumberFormatter;
if (nb.Description is not null) numBox.Description = nb.Description;
if (nb.Header is not null) numBox.Header = nb.Header;
SetElementTag(numBox, nb);
if (nb.OnValueChanged is not null)
numBox.ValueChanged += (s, _) =>
{
var box = (WinUI.NumberBox)s!;
if (ChangeEchoSuppressor.ShouldSuppress(box)) return;
(GetElementTag(box) as NumberBoxElement)?.OnValueChanged?.Invoke(box.Value);
};
// Per-keystroke value fire for Immediate-mode controls. Registered
// unconditionally so that toggling .Immediate() between renders works
// without re-mounting — the handler re-checks the marker each fire.
numBox.RegisterPropertyChangedCallback(WinUI.NumberBox.TextProperty,
NumberBoxImmediateTextChanged);
numBox.Loaded += NumberBoxLoadedEnsureImmediateTextBox;
ApplySetters(nb.Setters, numBox);
return numBox;
}
// Spec 047 §14 Phase 3-final Batch B — widened to internal static so
// NumberBoxDescriptor can register the same captured-free trampolines
// via the .Immediate entry shape.
internal static readonly Microsoft.UI.Xaml.DependencyPropertyChangedCallback NumberBoxImmediateTextChanged =
(sender, _) =>
{
if (sender is not WinUI.NumberBox box) return;
HandleNumberBoxImmediateTextChanged(box, box.Text);
};
internal static void NumberBoxLoadedEnsureImmediateTextBox(object sender, RoutedEventArgs _)
{
if (sender is not WinUI.NumberBox box) return;
if (EnsureNumberBoxImmediateTextBoxWiring(box))
box.Loaded -= NumberBoxLoadedEnsureImmediateTextBox;
}
internal static bool EnsureNumberBoxImmediateTextBoxWiring(WinUI.NumberBox box)
{
var events = GetOrCreateEventState(box);
if (events.NumberBoxInnerTextChanged) return true;
box.ApplyTemplate();
var input = FindDescendant<TextBox>(box);
if (input is null) return false;
events.NumberBoxInnerTextChanged = true;
input.TextChanged += (_, _) => HandleNumberBoxImmediateTextChanged(box, input.Text);
return true;
}
internal static T? FindDescendant<T>(DependencyObject root) where T : DependencyObject
{
int count = Microsoft.UI.Xaml.Media.VisualTreeHelper.GetChildrenCount(root);
for (int i = 0; i < count; i++)
{
var child = Microsoft.UI.Xaml.Media.VisualTreeHelper.GetChild(root, i);
if (child is T match) return match;
var nested = FindDescendant<T>(child);
if (nested is not null) return nested;
}
return null;
}
internal static void HandleNumberBoxImmediateTextChanged(WinUI.NumberBox box, string text)
{
if (GetElementTag(box) is not NumberBoxElement el) return;
if (el.OnValueChanged is null) return;
if (el.GetAttached<Microsoft.UI.Reactor.Controls.Validation.ImmediateValueAttached>() is null) return;
if (!double.TryParse(text,
global::System.Globalization.NumberStyles.Float,
global::System.Globalization.CultureInfo.CurrentCulture, out var parsed)) return;
// Reject NaN/±Infinity — double.TryParse accepts the literal strings
// "NaN"/"Infinity" by default, and NaN comparisons are never equal,
// so the sync-guard below would let them through.
if (!double.IsFinite(parsed)) return;
if (parsed < el.Minimum || parsed > el.Maximum) return;
if (AreNumberBoxValuesEquivalent(parsed, el.Value)) return; // already in sync; suppresses post-programmatic-write callback
if (CanSynchronizeNumberBoxImmediateValueWithoutReformat(el, text, parsed)
&& !AreNumberBoxValuesEquivalent(box.Value, parsed))
{
ChangeEchoSuppressor.BeginSuppress(box);
box.Value = parsed;
}
el.OnValueChanged.Invoke(parsed);
}
private WinUI.AutoSuggestBox MountAutoSuggestBox(AutoSuggestBoxElement asb)
{
var box = new WinUI.AutoSuggestBox { Text = asb.Text, PlaceholderText = asb.PlaceholderText ?? "" };
if (asb.Suggestions.Length > 0) box.ItemsSource = asb.Suggestions;
if (asb.Header is not null) box.Header = asb.Header;
if (asb.QueryIcon is not null) box.QueryIcon = ResolveIcon(asb.QueryIcon, null);
if (asb.IsSuggestionListOpen) box.IsSuggestionListOpen = true;
SetElementTag(box, asb);
if (asb.OnTextChanged is not null)
box.TextChanged += (s, args) =>
{
if (args.Reason == WinUI.AutoSuggestionBoxTextChangeReason.UserInput)
(GetElementTag((UIElement)s!) as AutoSuggestBoxElement)?.OnTextChanged?.Invoke(((WinUI.AutoSuggestBox)s!).Text);
};
if (asb.OnQuerySubmitted is not null)
box.QuerySubmitted += (s, args) =>
(GetElementTag((UIElement)s!) as AutoSuggestBoxElement)?.OnQuerySubmitted?.Invoke(args.QueryText);
if (asb.OnSuggestionChosen is not null)
box.SuggestionChosen += (s, args) =>
(GetElementTag((UIElement)s!) as AutoSuggestBoxElement)?.OnSuggestionChosen?.Invoke(args.SelectedItem?.ToString() ?? "");
ApplySetters(asb.Setters, box);
return box;
}
internal WinUI.CheckBox MountCheckBox(CheckBoxElement cb)
{
var checkBox = new WinUI.CheckBox { Content = cb.Label };
if (cb.IsThreeState)
{
checkBox.IsThreeState = true;
checkBox.IsChecked = cb.CheckedState;
}
else
{
checkBox.IsChecked = cb.IsChecked;
}
SetElementTag(checkBox, cb);
if (cb.OnIsCheckedChanged is not null || cb.OnCheckedStateChanged is not null)
{
checkBox.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);
};
checkBox.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);
};
checkBox.Indeterminate += (s, _) =>
{
var c = (UIElement)s!;
if (ChangeEchoSuppressor.ShouldSuppress(c)) return;
var el = GetElementTag(c) as CheckBoxElement;
el?.OnCheckedStateChanged?.Invoke(null);
};
}
ApplySetters(cb.Setters, checkBox);
return checkBox;
}
private WinUI.RadioButton MountRadioButton(RadioButtonElement rb)
{
var radio = new WinUI.RadioButton { Content = rb.Label, IsChecked = rb.IsChecked };
if (rb.GroupName is not null) radio.GroupName = rb.GroupName;
SetElementTag(radio, rb);
if (rb.OnIsCheckedChanged is not null)
{
radio.Checked += (s, _) =>
{
var c = (UIElement)s!;
if (ChangeEchoSuppressor.ShouldSuppress(c)) return;
(GetElementTag(c) as RadioButtonElement)?.OnIsCheckedChanged?.Invoke(true);
};
radio.Unchecked += (s, _) =>
{
var c = (UIElement)s!;
if (ChangeEchoSuppressor.ShouldSuppress(c)) return;
(GetElementTag(c) as RadioButtonElement)?.OnIsCheckedChanged?.Invoke(false);
};
}
ApplySetters(rb.Setters, radio);
return radio;
}
private WinUI.RadioButtons MountRadioButtons(RadioButtonsElement rbs)
{
var rbGroup = new WinUI.RadioButtons { SelectedIndex = rbs.SelectedIndex };
if (rbs.Header is not null) rbGroup.Header = rbs.Header;
foreach (var item in rbs.Items) rbGroup.Items.Add(item);
SetElementTag(rbGroup, rbs);
if (rbs.OnSelectedIndexChanged is not null)
rbGroup.SelectionChanged += (s, _) =>
{
var g = (WinUI.RadioButtons)s!;
if (ChangeEchoSuppressor.ShouldSuppress(g)) return;
(GetElementTag(g) as RadioButtonsElement)?.OnSelectedIndexChanged?.Invoke(g.SelectedIndex);
};
ApplySetters(rbs.Setters, rbGroup);
return rbGroup;
}
private WinUI.ComboBox MountComboBox(ComboBoxElement combo, Action requestRerender)
{
var cb = new WinUI.ComboBox
{
SelectedIndex = combo.SelectedIndex,
PlaceholderText = combo.PlaceholderText ?? "",
IsEditable = combo.IsEditable,
};
if (combo.Header is not null) cb.Header = combo.Header;
if (!double.IsNaN(combo.MaxDropDownHeight)) cb.MaxDropDownHeight = combo.MaxDropDownHeight;
if (combo.Description is not null) cb.Description = combo.Description;
if (combo.ItemElements is { } elements)
foreach (var el in elements) cb.Items.Add(Mount(el, requestRerender));
else
foreach (var item in combo.Items) cb.Items.Add(item);
SetElementTag(cb, combo);
if (combo.OnSelectedIndexChanged is not null)
cb.SelectionChanged += (s, _) =>
{
var c = (WinUI.ComboBox)s!;
if (ChangeEchoSuppressor.ShouldSuppress(c)) return;
(GetElementTag(c) as ComboBoxElement)?.OnSelectedIndexChanged?.Invoke(c.SelectedIndex);
};
if (combo.OnDropDownOpened is not null)
cb.DropDownOpened += (s, _) => (GetElementTag((UIElement)s!) as ComboBoxElement)?.OnDropDownOpened?.Invoke();
if (combo.OnDropDownClosed is not null)
cb.DropDownClosed += (s, _) => (GetElementTag((UIElement)s!) as ComboBoxElement)?.OnDropDownClosed?.Invoke();
ApplySetters(combo.Setters, cb);
return cb;
}
private WinUI.Slider MountSlider(SliderElement sl)
{
var slider = new WinUI.Slider
{
Value = sl.Value, Minimum = sl.Min, Maximum = sl.Max, StepFrequency = sl.StepFrequency,
Orientation = sl.Orientation,
TickFrequency = sl.TickFrequency,
TickPlacement = sl.TickPlacement,
SnapsTo = sl.SnapsTo,
IsThumbToolTipEnabled = sl.IsThumbToolTipEnabled,
};
if (sl.Header is not null) slider.Header = sl.Header;
SetElementTag(slider, sl);
if (sl.OnValueChanged is not null)
slider.ValueChanged += (_, args) =>
{
if (ChangeEchoSuppressor.ShouldSuppress(slider)) return;
(GetElementTag(slider) as SliderElement)?.OnValueChanged?.Invoke(args.NewValue);
};
ApplySetters(sl.Setters, slider);
return slider;
}
private WinUI.ToggleSwitch MountToggleSwitch(ToggleSwitchElement ts)
{
var rented = _pool.TryRent(typeof(WinUI.ToggleSwitch));
var toggle = rented as WinUI.ToggleSwitch ?? new WinUI.ToggleSwitch();
// SetElementTag BEFORE IsOn= so a pooled control's retained handler
// sees this mount's element, not the pool's last owner. Suppress the
// echo fired by the programmatic IsOn write when it actually changes.
SetElementTag(toggle, ts);
if (rented is not null && toggle.IsOn != ts.IsOn)
ChangeEchoSuppressor.BeginSuppress(toggle);
toggle.IsOn = ts.IsOn;
toggle.OnContent = ts.OnContent;
toggle.OffContent = ts.OffContent;
if (ts.Header is not null) toggle.Header = ts.Header;
EnsureToggleSwitchWiring(toggle, ts);
ApplySetters(ts.Setters, toggle);
return toggle;
}
// Dedupe via EventHandlerState (attached on ReactorAttached.StateProperty,
// keyed by native DependencyObject identity). A plain CWT keyed by managed
// RCW identity is unsafe — two RCWs over the same DO miss the dedupe and
// double-subscribe, fanning one Toggled into multiple user-callback invocations.
internal static void EnsureToggleSwitchWiring(WinUI.ToggleSwitch toggle, ToggleSwitchElement ts)
{
if (ts.OnIsOnChanged is null) return;
var state = GetOrCreateEventState(toggle);
if (state.ToggleSwitchToggledTrampoline is not null) return;
state.ToggleSwitchToggledTrampoline = (s, _) =>
{
var t = (WinUI.ToggleSwitch)s!;
if (ChangeEchoSuppressor.ShouldSuppress(t)) return;
(GetElementTag(t) as ToggleSwitchElement)?.OnIsOnChanged?.Invoke(t.IsOn);
};
toggle.Toggled += state.ToggleSwitchToggledTrampoline;
}
private WinUI.RatingControl MountRatingControl(RatingControlElement rc)
{
var rating = new WinUI.RatingControl
{
Value = rc.Value,
MaxRating = rc.MaxRating,
IsReadOnly = rc.IsReadOnly,
Caption = rc.Caption ?? "",
PlaceholderValue = rc.PlaceholderValue,
InitialSetValue = rc.InitialSetValue,
};
SetElementTag(rating, rc);
if (rc.OnValueChanged is not null)
rating.ValueChanged += (s, _) =>
{
var r = (WinUI.RatingControl)s!;
if (ChangeEchoSuppressor.ShouldSuppress(r)) return;
(GetElementTag(r) as RatingControlElement)?.OnValueChanged?.Invoke(r.Value);
};
ApplySetters(rc.Setters, rating);
return rating;
}
private WinUI.ColorPicker MountColorPicker(ColorPickerElement cp)
{
var picker = new WinUI.ColorPicker
{
Color = cp.Color, IsAlphaEnabled = cp.IsAlphaEnabled, IsMoreButtonVisible = cp.IsMoreButtonVisible,
IsColorSpectrumVisible = cp.IsColorSpectrumVisible, IsColorSliderVisible = cp.IsColorSliderVisible,
IsColorChannelTextInputVisible = cp.IsColorChannelTextInputVisible, IsHexInputVisible = cp.IsHexInputVisible,
ColorSpectrumShape = cp.ColorSpectrumShape,
MinHue = cp.MinHue, MaxHue = cp.MaxHue,
MinSaturation = cp.MinSaturation, MaxSaturation = cp.MaxSaturation,
MinValue = cp.MinValue, MaxValue = cp.MaxValue,
};
SetElementTag(picker, cp);
if (cp.OnColorChanged is not null)
picker.ColorChanged += (s, args) =>
{
var c = (UIElement)s!;
if (ChangeEchoSuppressor.ShouldSuppress(c)) return;
(GetElementTag(c) as ColorPickerElement)?.OnColorChanged?.Invoke(args.NewColor);
};
ApplySetters(cp.Setters, picker);
return picker;
}
private WinUI.CalendarDatePicker MountCalendarDatePicker(CalendarDatePickerElement cdp)
{
var cal = new WinUI.CalendarDatePicker { Date = cdp.Date, PlaceholderText = cdp.PlaceholderText ?? "" };
if (cdp.Header is not null) cal.Header = cdp.Header;
if (cdp.MinDate.HasValue) cal.MinDate = cdp.MinDate.Value;
if (cdp.MaxDate.HasValue) cal.MaxDate = cdp.MaxDate.Value;
if (cdp.DateFormat is not null) cal.DateFormat = cdp.DateFormat;
cal.IsTodayHighlighted = cdp.IsTodayHighlighted;
cal.IsGroupLabelVisible = cdp.IsGroupLabelVisible;
if (cdp.IsCalendarOpen) cal.IsCalendarOpen = true;
SetElementTag(cal, cdp);
if (cdp.OnDateChanged is not null)
cal.DateChanged += (s, _) =>
{
var c = (WinUI.CalendarDatePicker)s!;
if (ChangeEchoSuppressor.ShouldSuppress(c)) return;
(GetElementTag(c) as CalendarDatePickerElement)?.OnDateChanged?.Invoke(c.Date);
};
ApplySetters(cdp.Setters, cal);
return cal;
}
private WinUI.DatePicker MountDatePicker(DatePickerElement dp)
{
var picker = new WinUI.DatePicker
{
Date = dp.Date,
DayVisible = dp.DayVisible,
MonthVisible = dp.MonthVisible,
YearVisible = dp.YearVisible,
Orientation = dp.Orientation,
};
if (dp.Header is not null) picker.Header = dp.Header;
if (dp.MinYear.HasValue) picker.MinYear = dp.MinYear.Value;
if (dp.MaxYear.HasValue) picker.MaxYear = dp.MaxYear.Value;
if (dp.DayFormat is not null) picker.DayFormat = dp.DayFormat;
if (dp.MonthFormat is not null) picker.MonthFormat = dp.MonthFormat;
if (dp.YearFormat is not null) picker.YearFormat = dp.YearFormat;
SetElementTag(picker, dp);
if (dp.OnDateChanged is not null)
picker.DateChanged += (s, args) =>
{
var c = (UIElement)s!;
if (ChangeEchoSuppressor.ShouldSuppress(c)) return;
(GetElementTag(c) as DatePickerElement)?.OnDateChanged?.Invoke(args.NewDate);
};
ApplySetters(dp.Setters, picker);
return picker;
}
private WinUI.TimePicker MountTimePicker(TimePickerElement tp)
{
var picker = new WinUI.TimePicker { Time = tp.Time, MinuteIncrement = tp.MinuteIncrement };
if (tp.Header is not null) picker.Header = tp.Header;
SetElementTag(picker, tp);
if (tp.OnTimeChanged is not null)
picker.TimeChanged += (s, args) =>
{
var c = (UIElement)s!;
if (ChangeEchoSuppressor.ShouldSuppress(c)) return;
(GetElementTag(c) as TimePickerElement)?.OnTimeChanged?.Invoke(args.NewTime);
};
ApplySetters(tp.Setters, picker);
return picker;
}
private WinUI.ProgressBar MountProgress(ProgressElement prog)
{
var bar = _pool.TryRent(typeof(WinUI.ProgressBar)) as WinUI.ProgressBar ?? new WinUI.ProgressBar();
bar.IsIndeterminate = prog.IsIndeterminate;
bar.Minimum = prog.Minimum;
bar.Maximum = prog.Maximum;
bar.ShowError = prog.ShowError;
bar.ShowPaused = prog.ShowPaused;
if (prog.Value.HasValue) bar.Value = prog.Value.Value;
ApplySetters(prog.Setters, bar);
return bar;
}
private WinUI.ProgressRing MountProgressRing(ProgressRingElement ring)
{
var pr = _pool.TryRent(typeof(WinUI.ProgressRing)) as WinUI.ProgressRing ?? new WinUI.ProgressRing();
pr.IsIndeterminate = ring.IsIndeterminate;
pr.IsActive = ring.IsActive;
pr.Minimum = ring.Minimum;
pr.Maximum = ring.Maximum;
if (ring.Value.HasValue) pr.Value = ring.Value.Value;
ApplySetters(ring.Setters, pr);
return pr;
}
private WinUI.Image MountImage(ImageElement img)
{
var image = _pool.TryRent(typeof(WinUI.Image)) as WinUI.Image ?? new WinUI.Image();
// Tag + wire BEFORE assigning Source — small/cached images can fire
// ImageOpened/ImageFailed synchronously during Source assignment.
SetElementTag(image, img);
EnsureImageWiring(image);
try
{
var uri = new Uri(img.Source, UriKind.RelativeOrAbsolute);