winrt-xaml 1.0.0

A Rust library for creating modern Windows UIs using WinRT and XAML with reactive data binding
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
//! Safe Rust wrappers for XAML Islands via C++ helper DLL.
//!
//! This module provides a safe API for creating and managing WinRT XAML controls
//! through a C++ bridge that handles the complex COM interop.

pub mod ffi;
mod resource_dictionary;
mod animation;

pub use resource_dictionary::*;
pub use animation::*;

use crate::error::{Error, Result};
use windows::Win32::Foundation::HWND;

fn to_wide_string(s: &str) -> Vec<u16> {
    s.encode_utf16().chain(Some(0)).collect()
}

// ===== XAML Manager =====

/// Manages the Windows XAML framework.
/// Must be kept alive for the duration of XAML usage.
pub struct XamlManager {
    handle: ffi::XamlManagerHandle,
}

impl XamlManager {
    /// Initialize the XAML framework for the current thread.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_initialize() };
        if handle.0.is_null() {
            return Err(Error::initialization("Failed to initialize XAML Manager".to_string()));
        }
        Ok(XamlManager { handle })
    }
}

impl Drop for XamlManager {
    fn drop(&mut self) {
        unsafe {
            ffi::xaml_uninitialize(self.handle);
        }
    }
}

unsafe impl Send for XamlManager {}
unsafe impl Sync for XamlManager {}

// ===== XAML Source (DesktopWindowXamlSource) =====

/// Represents a DesktopWindowXamlSource for hosting XAML content.
pub struct XamlSource {
    handle: ffi::XamlSourceHandle,
    island_hwnd: Option<HWND>,
}

impl XamlSource {
    /// Create a new XAML source.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_source_create() };
        if handle.0.is_null() {
            return Err(Error::control_creation("Failed to create XAML Source".to_string()));
        }
        Ok(XamlSource {
            handle,
            island_hwnd: None,
        })
    }

    /// Attach the XAML source to a parent Win32 window.
    pub fn attach_to_window(&mut self, parent_hwnd: HWND) -> Result<HWND> {
        let island_hwnd = unsafe { ffi::xaml_source_attach_to_window(self.handle, parent_hwnd) };
        if island_hwnd.0.is_null() {
            return Err(Error::window_creation("Failed to attach XAML Source".to_string()));
        }
        self.island_hwnd = Some(island_hwnd);
        Ok(island_hwnd)
    }

    /// Set the content to a Button.
    pub fn set_content(&self, button: &XamlButton) -> Result<()> {
        let result = unsafe { ffi::xaml_source_set_content(self.handle, button.handle) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set content".to_string()));
        }
        Ok(())
    }

    /// Set the content to any UIElement.
    pub fn set_content_element(&self, element: &XamlUIElement) -> Result<()> {
        let result = unsafe { ffi::xaml_source_set_content_generic(self.handle, element.handle) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set content element".to_string()));
        }
        Ok(())
    }

    /// Get the XAML island HWND (if attached).
    pub fn island_hwnd(&self) -> Option<HWND> {
        self.island_hwnd
    }
}

impl Drop for XamlSource {
    fn drop(&mut self) {
        unsafe {
            ffi::xaml_source_destroy(self.handle);
        }
    }
}

unsafe impl Send for XamlSource {}
unsafe impl Sync for XamlSource {}

// ===== UIElement (Base Type) =====

/// Represents a generic WinRT UIElement.
pub struct XamlUIElement {
    handle: ffi::XamlUIElementHandle,
}

impl XamlUIElement {
    /// Create from a raw handle (internal use).
    pub(crate) fn from_handle(handle: ffi::XamlUIElementHandle) -> Self {
        XamlUIElement { handle }
    }

    /// Get the raw handle.
    pub fn handle(&self) -> ffi::XamlUIElementHandle {
        self.handle
    }

    /// Set the Grid.Row attached property.
    pub fn set_grid_row(&self, row: i32) -> Result<()> {
        let result = unsafe { ffi::xaml_grid_set_child_row(self.handle, row) };
        if result != 0 {
            return Err(Error::invalid_operation("Failed to set grid row".to_string()));
        }
        Ok(())
    }

    /// Set the Grid.Column attached property.
    pub fn set_grid_column(&self, column: i32) -> Result<()> {
        let result = unsafe { ffi::xaml_grid_set_child_column(self.handle, column) };
        if result != 0 {
            return Err(Error::invalid_operation("Failed to set grid column".to_string()));
        }
        Ok(())
    }

    /// Set the Grid.RowSpan attached property.
    pub fn set_grid_row_span(&self, row_span: i32) -> Result<()> {
        let result = unsafe { ffi::xaml_grid_set_child_row_span(self.handle, row_span) };
        if result != 0 {
            return Err(Error::invalid_operation("Failed to set grid row span".to_string()));
        }
        Ok(())
    }

    /// Set the Grid.ColumnSpan attached property.
    pub fn set_grid_column_span(&self, column_span: i32) -> Result<()> {
        let result = unsafe { ffi::xaml_grid_set_child_column_span(self.handle, column_span) };
        if result != 0 {
            return Err(Error::invalid_operation("Failed to set grid column span".to_string()));
        }
        Ok(())
    }
}

unsafe impl Send for XamlUIElement {}
unsafe impl Sync for XamlUIElement {}

// ===== Button =====

/// WinRT Button control.
pub struct XamlButton {
    handle: ffi::XamlButtonHandle,
}

impl XamlButton {
    /// Create a new WinRT Button.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_button_create() };
        if handle.0.is_null() {
            return Err(Error::control_creation("Failed to create Button".to_string()));
        }
        Ok(XamlButton { handle })
    }

    /// Set the button content (text).
    pub fn set_content(&self, content: &str) -> Result<()> {
        let wide_content = to_wide_string(content);
        let result = unsafe { ffi::xaml_button_set_content(self.handle, wide_content.as_ptr()) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set button content".to_string()));
        }
        Ok(())
    }

    /// Set the button size (width and height).
    pub fn set_size(&self, width: f64, height: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_button_set_size(self.handle, width, height) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set button size".to_string()));
        }
        Ok(())
    }

    /// Register a click event handler.
    /// The callback will be called when the button is clicked.
    /// Note: The callback must be 'static and will be leaked to ensure it remains valid.
    pub fn on_click<F>(&self, callback: F) -> Result<()>
    where
        F: Fn() + Send + 'static,
    {
        // Box the callback and convert to a raw pointer
        let boxed_callback = Box::new(callback);
        let user_data = Box::into_raw(boxed_callback) as *mut std::ffi::c_void;

        // Define the C callback that will be called by C++
        extern "C" fn trampoline<F>(user_data: *mut std::ffi::c_void)
        where
            F: Fn(),
        {
            unsafe {
                let callback = &*(user_data as *const F);
                callback();
            }
        }

        // Register the click handler
        let result = unsafe {
            ffi::xaml_button_register_click(
                self.handle,
                trampoline::<F>,
                user_data,
            )
        };

        if result != 0 {
            // If registration failed, clean up the leaked box
            unsafe {
                let _ = Box::from_raw(user_data as *mut F);
            }
            return Err(Error::control_creation("Failed to register click handler".to_string()));
        }

        // Note: The callback is intentionally leaked and will remain valid for the button's lifetime
        // In a production app, you'd want to store the pointer and clean it up in Drop
        Ok(())
    }

    /// Set the button background color (ARGB format: 0xAARRGGBB).
    pub fn set_background(&self, color: u32) -> Result<()> {
        let result = unsafe { ffi::xaml_button_set_background(self.handle, color) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set background".to_string()));
        }
        Ok(())
    }

    /// Set the button foreground (text) color (ARGB format: 0xAARRGGBB).
    pub fn set_foreground(&self, color: u32) -> Result<()> {
        let result = unsafe { ffi::xaml_button_set_foreground(self.handle, color) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set foreground".to_string()));
        }
        Ok(())
    }

    /// Set the button corner radius for rounded corners.
    pub fn set_corner_radius(&self, radius: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_button_set_corner_radius(self.handle, radius) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set corner radius".to_string()));
        }
        Ok(())
    }

    /// Set the button padding (inner spacing).
    pub fn set_padding(&self, left: f64, top: f64, right: f64, bottom: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_button_set_padding(self.handle, left, top, right, bottom) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set padding".to_string()));
        }
        Ok(())
    }

    /// Convert to UIElement for use in layout containers.
    pub fn as_uielement(&self) -> XamlUIElement {
        let handle = unsafe { ffi::xaml_button_as_uielement(self.handle) };
        XamlUIElement::from_handle(handle)
    }
}

impl Drop for XamlButton {
    fn drop(&mut self) {
        unsafe {
            ffi::xaml_button_destroy(self.handle);
        }
    }
}

unsafe impl Send for XamlButton {}
unsafe impl Sync for XamlButton {}

// ===== TextBlock =====

/// WinRT TextBlock control.
pub struct XamlTextBlock {
    handle: ffi::XamlTextBlockHandle,
}

impl XamlTextBlock {
    /// Create a new WinRT TextBlock.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_textblock_create() };
        if handle.0.is_null() {
            return Err(Error::control_creation("Failed to create TextBlock".to_string()));
        }
        Ok(XamlTextBlock { handle })
    }

    /// Set the text content.
    pub fn set_text(&self, text: &str) -> Result<()> {
        let wide_text = to_wide_string(text);
        let result = unsafe { ffi::xaml_textblock_set_text(self.handle, wide_text.as_ptr()) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set text".to_string()));
        }
        Ok(())
    }

    /// Set the font size.
    pub fn set_font_size(&self, size: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_textblock_set_font_size(self.handle, size) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set font size".to_string()));
        }
        Ok(())
    }

    /// Set the text foreground color (ARGB format: 0xAARRGGBB).
    pub fn set_foreground(&self, color: u32) -> Result<()> {
        let result = unsafe { ffi::xaml_textblock_set_foreground(self.handle, color) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set foreground".to_string()));
        }
        Ok(())
    }

    /// Set the font weight (400=Normal, 600=SemiBold, 700=Bold).
    pub fn set_font_weight(&self, weight: i32) -> Result<()> {
        let result = unsafe { ffi::xaml_textblock_set_font_weight(self.handle, weight) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set font weight".to_string()));
        }
        Ok(())
    }

    /// Set the margin (outer spacing).
    pub fn set_margin(&self, left: f64, top: f64, right: f64, bottom: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_textblock_set_margin(self.handle, left, top, right, bottom) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set margin".to_string()));
        }
        Ok(())
    }

    /// Convert to UIElement for use in layout containers.
    pub fn as_uielement(&self) -> XamlUIElement {
        let handle = unsafe { ffi::xaml_textblock_as_uielement(self.handle) };
        XamlUIElement::from_handle(handle)
    }
}

impl Drop for XamlTextBlock {
    fn drop(&mut self) {
        unsafe {
            ffi::xaml_textblock_destroy(self.handle);
        }
    }
}

unsafe impl Send for XamlTextBlock {}
unsafe impl Sync for XamlTextBlock {}

// ===== TextBox =====

/// WinRT TextBox control.
pub struct XamlTextBox {
    handle: ffi::XamlTextBoxHandle,
}

impl XamlTextBox {
    /// Create a new WinRT TextBox.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_textbox_create() };
        if handle.0.is_null() {
            return Err(Error::control_creation("Failed to create TextBox".to_string()));
        }
        Ok(XamlTextBox { handle })
    }

    /// Set the text content.
    pub fn set_text(&self, text: &str) -> Result<()> {
        let wide_text = to_wide_string(text);
        let result = unsafe { ffi::xaml_textbox_set_text(self.handle, wide_text.as_ptr()) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set text".to_string()));
        }
        Ok(())
    }

    /// Get the current text content.
    pub fn get_text(&self) -> Result<String> {
        const BUFFER_SIZE: i32 = 1024;
        let mut buffer: Vec<u16> = vec![0; BUFFER_SIZE as usize];

        let result = unsafe {
            ffi::xaml_textbox_get_text(self.handle, buffer.as_mut_ptr(), BUFFER_SIZE)
        };

        if result < 0 {
            return Err(Error::control_creation("Failed to get text".to_string()));
        }

        // Convert the wide string to Rust String
        let len = result as usize;
        let text = String::from_utf16_lossy(&buffer[..len]);
        Ok(text)
    }

    /// Set the placeholder text.
    pub fn set_placeholder(&self, placeholder: &str) -> Result<()> {
        let wide_placeholder = to_wide_string(placeholder);
        let result = unsafe { ffi::xaml_textbox_set_placeholder(self.handle, wide_placeholder.as_ptr()) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set placeholder".to_string()));
        }
        Ok(())
    }

    /// Set the text box size (width and height).
    pub fn set_size(&self, width: f64, height: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_textbox_set_size(self.handle, width, height) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set size".to_string()));
        }
        Ok(())
    }

    /// Set the textbox background color (ARGB format: 0xAARRGGBB).
    pub fn set_background(&self, color: u32) -> Result<()> {
        let result = unsafe { ffi::xaml_textbox_set_background(self.handle, color) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set background".to_string()));
        }
        Ok(())
    }

    /// Set the textbox foreground (text) color (ARGB format: 0xAARRGGBB).
    pub fn set_foreground(&self, color: u32) -> Result<()> {
        let result = unsafe { ffi::xaml_textbox_set_foreground(self.handle, color) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set foreground".to_string()));
        }
        Ok(())
    }

    /// Set the textbox corner radius for rounded corners.
    pub fn set_corner_radius(&self, radius: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_textbox_set_corner_radius(self.handle, radius) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set corner radius".to_string()));
        }
        Ok(())
    }

    /// Set the textbox padding (inner spacing).
    pub fn set_padding(&self, left: f64, top: f64, right: f64, bottom: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_textbox_set_padding(self.handle, left, top, right, bottom) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set padding".to_string()));
        }
        Ok(())
    }

    /// Convert to UIElement for use in layout containers.
    pub fn as_uielement(&self) -> XamlUIElement {
        let handle = unsafe { ffi::xaml_textbox_as_uielement(self.handle) };
        XamlUIElement::from_handle(handle)
    }

    /// Register a callback for when the text changes.
    pub fn on_text_changed<F>(&self, callback: F) -> Result<()>
    where
        F: Fn() + Send + Sync + 'static,
    {
        let boxed = Box::new(callback);
        let ptr = Box::into_raw(boxed);

        extern "C" fn trampoline<F>(user_data: *mut std::ffi::c_void)
        where
            F: Fn() + Send + Sync + 'static,
        {
            unsafe {
                let callback = &*(user_data as *const F);
                callback();
            }
        }

        unsafe {
            ffi::xaml_textbox_on_text_changed(
                self.handle,
                std::mem::transmute(trampoline::<F> as *const ())
            );
        }

        std::mem::forget(ptr);
        Ok(())
    }
}

impl Drop for XamlTextBox {
    fn drop(&mut self) {
        unsafe {
            ffi::xaml_textbox_destroy(self.handle);
        }
    }
}

unsafe impl Send for XamlTextBox {}
unsafe impl Sync for XamlTextBox {}

// ===== StackPanel =====

/// WinRT StackPanel layout container.
pub struct XamlStackPanel {
    handle: ffi::XamlStackPanelHandle,
}

impl XamlStackPanel {
    /// Create a new WinRT StackPanel.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_stackpanel_create() };
        if handle.0.is_null() {
            return Err(Error::control_creation("Failed to create StackPanel".to_string()));
        }
        Ok(XamlStackPanel { handle })
    }

    /// Add a child element to the panel.
    pub fn add_child(&self, child: &XamlUIElement) -> Result<()> {
        let result = unsafe { ffi::xaml_stackpanel_add_child(self.handle, child.handle) };
        if result != 0 {
            return Err(Error::control_creation("Failed to add child".to_string()));
        }
        Ok(())
    }

    /// Set the orientation (true = vertical, false = horizontal).
    pub fn set_vertical(&self, vertical: bool) -> Result<()> {
        let result = unsafe { ffi::xaml_stackpanel_set_orientation(self.handle, if vertical { 1 } else { 0 }) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set orientation".to_string()));
        }
        Ok(())
    }

    /// Set the orientation using the Orientation enum.
    pub fn set_orientation(&self, orientation: crate::layout::Orientation) -> Result<()> {
        use crate::layout::Orientation;
        self.set_vertical(orientation == Orientation::Vertical)
    }

    /// Set the spacing between children.
    pub fn set_spacing(&self, spacing: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_stackpanel_set_spacing(self.handle, spacing) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set spacing".to_string()));
        }
        Ok(())
    }

    /// Set the panel background color (ARGB format: 0xAARRGGBB).
    pub fn set_background(&self, color: u32) -> Result<()> {
        let result = unsafe { ffi::xaml_stackpanel_set_background(self.handle, color) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set background".to_string()));
        }
        Ok(())
    }

    /// Set the panel padding (inner spacing).
    pub fn set_padding(&self, left: f64, top: f64, right: f64, bottom: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_stackpanel_set_padding(self.handle, left, top, right, bottom) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set padding".to_string()));
        }
        Ok(())
    }

    /// Set the panel corner radius for rounded corners.
    pub fn set_corner_radius(&self, radius: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_stackpanel_set_corner_radius(self.handle, radius) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set corner radius".to_string()));
        }
        Ok(())
    }

    /// Convert to UIElement for use in layout containers.
    pub fn as_uielement(&self) -> XamlUIElement {
        let handle = unsafe { ffi::xaml_stackpanel_as_uielement(self.handle) };
        XamlUIElement::from_handle(handle)
    }
}

impl Drop for XamlStackPanel {
    fn drop(&mut self) {
        unsafe {
            ffi::xaml_stackpanel_destroy(self.handle);
        }
    }
}

unsafe impl Send for XamlStackPanel {}
unsafe impl Sync for XamlStackPanel {}

// ===== Grid =====

/// WinRT Grid layout container.
pub struct XamlGrid {
    handle: ffi::XamlGridHandle,
}

impl XamlGrid {
    /// Create a new WinRT Grid.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_grid_create() };
        if handle.0.is_null() {
            return Err(Error::control_creation("Failed to create Grid".to_string()));
        }
        Ok(XamlGrid { handle })
    }

    /// Add a child element to the grid.
    pub fn add_child(&self, child: &XamlUIElement) -> Result<()> {
        let result = unsafe { ffi::xaml_grid_add_child(self.handle, child.handle) };
        if result != 0 {
            return Err(Error::control_creation("Failed to add child".to_string()));
        }
        Ok(())
    }

    /// Set the grid background color (ARGB format: 0xAARRGGBB).
    pub fn set_background(&self, color: u32) -> Result<()> {
        let result = unsafe { ffi::xaml_grid_set_background(self.handle, color) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set background".to_string()));
        }
        Ok(())
    }

    /// Set the grid padding (inner spacing).
    pub fn set_padding(&self, left: f64, top: f64, right: f64, bottom: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_grid_set_padding(self.handle, left, top, right, bottom) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set padding".to_string()));
        }
        Ok(())
    }

    /// Set the grid corner radius for rounded corners.
    pub fn set_corner_radius(&self, radius: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_grid_set_corner_radius(self.handle, radius) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set corner radius".to_string()));
        }
        Ok(())
    }

    /// Add a row definition with pixel height.
    pub fn add_row_pixels(&self, height: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_grid_add_row_definition(self.handle, height, 0, 0) };
        if result != 0 {
            return Err(Error::control_creation("Failed to add row definition".to_string()));
        }
        Ok(())
    }

    /// Add a row definition with Auto sizing.
    pub fn add_row_auto(&self) -> Result<()> {
        let result = unsafe { ffi::xaml_grid_add_row_definition(self.handle, 0.0, 1, 0) };
        if result != 0 {
            return Err(Error::control_creation("Failed to add row definition".to_string()));
        }
        Ok(())
    }

    /// Add a row definition with Star sizing (proportional).
    pub fn add_row_star(&self, proportion: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_grid_add_row_definition(self.handle, proportion, 0, 1) };
        if result != 0 {
            return Err(Error::control_creation("Failed to add row definition".to_string()));
        }
        Ok(())
    }

    /// Add a column definition with pixel width.
    pub fn add_column_pixels(&self, width: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_grid_add_column_definition(self.handle, width, 0, 0) };
        if result != 0 {
            return Err(Error::control_creation("Failed to add column definition".to_string()));
        }
        Ok(())
    }

    /// Add a column definition with Auto sizing.
    pub fn add_column_auto(&self) -> Result<()> {
        let result = unsafe { ffi::xaml_grid_add_column_definition(self.handle, 0.0, 1, 0) };
        if result != 0 {
            return Err(Error::control_creation("Failed to add column definition".to_string()));
        }
        Ok(())
    }

    /// Add a column definition with Star sizing (proportional).
    pub fn add_column_star(&self, proportion: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_grid_add_column_definition(self.handle, proportion, 0, 1) };
        if result != 0 {
            return Err(Error::control_creation("Failed to add column definition".to_string()));
        }
        Ok(())
    }

    /// Convert to UIElement for use in layout containers.
    pub fn as_uielement(&self) -> XamlUIElement {
        let handle = unsafe { ffi::xaml_grid_as_uielement(self.handle) };
        XamlUIElement::from_handle(handle)
    }
}

impl Drop for XamlGrid {
    fn drop(&mut self) {
        unsafe {
            ffi::xaml_grid_destroy(self.handle);
        }
    }
}

unsafe impl Send for XamlGrid {}
unsafe impl Sync for XamlGrid {}

// ===== ScrollViewer =====

/// Represents a WinRT ScrollViewer control that provides scrollable content.
pub struct XamlScrollViewer {
    handle: ffi::XamlScrollViewerHandle,
}

/// Scroll mode for ScrollViewer
pub enum ScrollMode {
    Disabled = 0,
    Enabled = 1,
    Auto = 2,
}

/// Scroll bar visibility for ScrollViewer
pub enum ScrollBarVisibility {
    Disabled = 0,
    Auto = 1,
    Hidden = 2,
    Visible = 3,
}

impl XamlScrollViewer {
    /// Create a new WinRT ScrollViewer.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_scrollviewer_create() };
        if handle.0.is_null() {
            return Err(Error::control_creation("Failed to create ScrollViewer".to_string()));
        }
        Ok(XamlScrollViewer { handle })
    }

    /// Set the content of the ScrollViewer.
    pub fn set_content(&self, content: &XamlUIElement) -> Result<()> {
        let result = unsafe { ffi::xaml_scrollviewer_set_content(self.handle, content.handle) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set content".to_string()));
        }
        Ok(())
    }

    /// Set the horizontal scroll mode.
    pub fn set_horizontal_scroll_mode(&self, mode: ScrollMode) -> Result<()> {
        let result = unsafe { ffi::xaml_scrollviewer_set_horizontal_scroll_mode(self.handle, mode as i32) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set horizontal scroll mode".to_string()));
        }
        Ok(())
    }

    /// Set the vertical scroll mode.
    pub fn set_vertical_scroll_mode(&self, mode: ScrollMode) -> Result<()> {
        let result = unsafe { ffi::xaml_scrollviewer_set_vertical_scroll_mode(self.handle, mode as i32) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set vertical scroll mode".to_string()));
        }
        Ok(())
    }

    /// Set the horizontal scroll bar visibility.
    pub fn set_horizontal_scrollbar_visibility(&self, visibility: ScrollBarVisibility) -> Result<()> {
        let result = unsafe { ffi::xaml_scrollviewer_set_horizontal_scroll_bar_visibility(self.handle, visibility as i32) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set horizontal scrollbar visibility".to_string()));
        }
        Ok(())
    }

    /// Set the vertical scroll bar visibility.
    pub fn set_vertical_scrollbar_visibility(&self, visibility: ScrollBarVisibility) -> Result<()> {
        let result = unsafe { ffi::xaml_scrollviewer_set_vertical_scroll_bar_visibility(self.handle, visibility as i32) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set vertical scrollbar visibility".to_string()));
        }
        Ok(())
    }

    /// Convert to a UIElement for use as content in other containers.
    pub fn as_uielement(&self) -> XamlUIElement {
        let handle = unsafe { ffi::xaml_scrollviewer_as_uielement(self.handle) };
        XamlUIElement { handle }
    }
}

impl Drop for XamlScrollViewer {
    fn drop(&mut self) {
        unsafe {
            ffi::xaml_scrollviewer_destroy(self.handle);
        }
    }
}

unsafe impl Send for XamlScrollViewer {}
unsafe impl Sync for XamlScrollViewer {}

// ===== CheckBox =====

/// A WinRT CheckBox control.
pub struct XamlCheckBox {
    handle: ffi::XamlCheckBoxHandle,
}

impl XamlCheckBox {
    /// Create a new CheckBox.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_checkbox_create() };
        if handle.0.is_null() {
            return Err(Error::control_creation("Failed to create CheckBox".to_string()));
        }
        Ok(XamlCheckBox { handle })
    }

    /// Set the content/label of the checkbox.
    pub fn set_content(&self, content: &str) -> Result<()> {
        let wide_content = to_wide_string(content);
        let result = unsafe { ffi::xaml_checkbox_set_content(self.handle, wide_content.as_ptr()) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set checkbox content".to_string()));
        }
        Ok(())
    }

    /// Set whether the checkbox is checked.
    pub fn set_is_checked(&self, is_checked: bool) -> Result<()> {
        let result = unsafe { ffi::xaml_checkbox_set_is_checked(self.handle, is_checked) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set checkbox state".to_string()));
        }
        Ok(())
    }

    /// Get whether the checkbox is checked.
    pub fn is_checked(&self) -> bool {
        unsafe { ffi::xaml_checkbox_get_is_checked(self.handle) }
    }

    /// Convert to a UIElement for use as content in other containers.
    pub fn as_uielement(&self) -> XamlUIElement {
        let handle = unsafe { ffi::xaml_checkbox_as_uielement(self.handle) };
        XamlUIElement { handle }
    }
}

unsafe impl Send for XamlCheckBox {}
unsafe impl Sync for XamlCheckBox {}

// ===== ComboBox =====

/// A WinRT ComboBox control.
pub struct XamlComboBox {
    handle: ffi::XamlComboBoxHandle,
}

impl XamlComboBox {
    /// Create a new ComboBox.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_combobox_create() };
        if handle.0.is_null() {
            return Err(Error::control_creation("Failed to create ComboBox".to_string()));
        }
        Ok(XamlComboBox { handle })
    }

    /// Add an item to the combobox.
    pub fn add_item(&self, item: &str) -> Result<()> {
        let wide_item = to_wide_string(item);
        let result = unsafe { ffi::xaml_combobox_add_item(self.handle, wide_item.as_ptr()) };
        if result != 0 {
            return Err(Error::control_creation("Failed to add combobox item".to_string()));
        }
        Ok(())
    }

    /// Set the selected index.
    pub fn set_selected_index(&self, index: i32) -> Result<()> {
        let result = unsafe { ffi::xaml_combobox_set_selected_index(self.handle, index) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set selected index".to_string()));
        }
        Ok(())
    }

    /// Get the selected index.
    pub fn get_selected_index(&self) -> i32 {
        unsafe { ffi::xaml_combobox_get_selected_index(self.handle) }
    }

    /// Convert to a UIElement for use as content in other containers.
    pub fn as_uielement(&self) -> XamlUIElement {
        let handle = unsafe { ffi::xaml_combobox_as_uielement(self.handle) };
        XamlUIElement { handle }
    }
}

unsafe impl Send for XamlComboBox {}
unsafe impl Sync for XamlComboBox {}

// ===== Slider =====

/// A WinRT Slider control.
pub struct XamlSlider {
    handle: ffi::XamlSliderHandle,
}

impl XamlSlider {
    /// Create a new Slider.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_slider_create() };
        if handle.0.is_null() {
            return Err(Error::control_creation("Failed to create Slider".to_string()));
        }
        Ok(XamlSlider { handle })
    }

    /// Set the minimum value.
    pub fn set_minimum(&self, minimum: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_slider_set_minimum(self.handle, minimum) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set slider minimum".to_string()));
        }
        Ok(())
    }

    /// Set the maximum value.
    pub fn set_maximum(&self, maximum: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_slider_set_maximum(self.handle, maximum) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set slider maximum".to_string()));
        }
        Ok(())
    }

    /// Set the current value.
    pub fn set_value(&self, value: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_slider_set_value(self.handle, value) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set slider value".to_string()));
        }
        Ok(())
    }

    /// Get the current value.
    pub fn get_value(&self) -> f64 {
        unsafe { ffi::xaml_slider_get_value(self.handle) }
    }

    /// Convert to a UIElement for use as content in other containers.
    pub fn as_uielement(&self) -> XamlUIElement {
        let handle = unsafe { ffi::xaml_slider_as_uielement(self.handle) };
        XamlUIElement { handle }
    }
}

unsafe impl Send for XamlSlider {}
unsafe impl Sync for XamlSlider {}

// ===== ProgressBar =====

/// A WinRT ProgressBar control.
pub struct XamlProgressBar {
    handle: ffi::XamlProgressBarHandle,
}

impl XamlProgressBar {
    /// Create a new ProgressBar.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_progressbar_create() };
        if handle.0.is_null() {
            return Err(Error::control_creation("Failed to create ProgressBar".to_string()));
        }
        Ok(XamlProgressBar { handle })
    }

    /// Set the minimum value.
    pub fn set_minimum(&self, minimum: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_progressbar_set_minimum(self.handle, minimum) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set progressbar minimum".to_string()));
        }
        Ok(())
    }

    /// Set the maximum value.
    pub fn set_maximum(&self, maximum: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_progressbar_set_maximum(self.handle, maximum) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set progressbar maximum".to_string()));
        }
        Ok(())
    }

    /// Set the current value.
    pub fn set_value(&self, value: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_progressbar_set_value(self.handle, value) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set progressbar value".to_string()));
        }
        Ok(())
    }

    /// Set whether the progress bar is indeterminate (animated).
    pub fn set_is_indeterminate(&self, is_indeterminate: bool) -> Result<()> {
        let result = unsafe { ffi::xaml_progressbar_set_is_indeterminate(self.handle, is_indeterminate) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set progressbar indeterminate state".to_string()));
        }
        Ok(())
    }

    /// Convert to a UIElement for use as content in other containers.
    pub fn as_uielement(&self) -> XamlUIElement {
        let handle = unsafe { ffi::xaml_progressbar_as_uielement(self.handle) };
        XamlUIElement { handle }
    }
}

unsafe impl Send for XamlProgressBar {}
unsafe impl Sync for XamlProgressBar {}

// ===== RadioButton =====

/// A WinRT RadioButton control for mutually exclusive selections.
pub struct XamlRadioButton {
    handle: ffi::XamlRadioButtonHandle,
}

impl XamlRadioButton {
    /// Create a new RadioButton.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_radiobutton_create() };
        if handle.0.is_null() {
            return Err(Error::control_creation("Failed to create RadioButton".to_string()));
        }
        Ok(XamlRadioButton { handle })
    }

    /// Set the content (label) of the radio button.
    pub fn set_content(&self, content: impl AsRef<str>) -> Result<()> {
        let content_wide = to_wide_string(content.as_ref());
        let result = unsafe { ffi::xaml_radiobutton_set_content(self.handle, content_wide.as_ptr()) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set radiobutton content".to_string()));
        }
        Ok(())
    }

    /// Set whether the radio button is checked.
    pub fn set_is_checked(&self, is_checked: bool) -> Result<()> {
        let result = unsafe { ffi::xaml_radiobutton_set_is_checked(self.handle, if is_checked { 1 } else { 0 }) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set radiobutton checked state".to_string()));
        }
        Ok(())
    }

    /// Get whether the radio button is checked.
    pub fn is_checked(&self) -> bool {
        let result = unsafe { ffi::xaml_radiobutton_get_is_checked(self.handle) };
        result != 0
    }

    /// Set the group name for mutual exclusivity.
    /// Radio buttons with the same group name are mutually exclusive.
    pub fn set_group_name(&self, group_name: impl AsRef<str>) -> Result<()> {
        let group_wide = to_wide_string(group_name.as_ref());
        let result = unsafe { ffi::xaml_radiobutton_set_group_name(self.handle, group_wide.as_ptr()) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set radiobutton group name".to_string()));
        }
        Ok(())
    }

    /// Register a callback for when the radio button is checked.
    pub fn on_checked<F>(&self, callback: F) -> Result<()>
    where
        F: Fn() + Send + Sync + 'static,
    {
        let boxed = Box::new(callback);
        let ptr = Box::into_raw(boxed);

        extern "C" fn trampoline<F>(user_data: *mut std::ffi::c_void)
        where
            F: Fn() + Send + Sync + 'static,
        {
            unsafe {
                let callback = &*(user_data as *const F);
                callback();
            }
        }

        unsafe {
            ffi::xaml_radiobutton_on_checked(
                self.handle,
                std::mem::transmute(trampoline::<F> as *const ())
            );
        }

        // Note: This leaks the callback. In production, you'd want proper cleanup.
        std::mem::forget(ptr);
        Ok(())
    }

    /// Register a callback for when the radio button is unchecked.
    pub fn on_unchecked<F>(&self, callback: F) -> Result<()>
    where
        F: Fn() + Send + Sync + 'static,
    {
        let boxed = Box::new(callback);
        let ptr = Box::into_raw(boxed);

        extern "C" fn trampoline<F>(user_data: *mut std::ffi::c_void)
        where
            F: Fn() + Send + Sync + 'static,
        {
            unsafe {
                let callback = &*(user_data as *const F);
                callback();
            }
        }

        unsafe {
            ffi::xaml_radiobutton_on_unchecked(
                self.handle,
                std::mem::transmute(trampoline::<F> as *const ())
            );
        }

        std::mem::forget(ptr);
        Ok(())
    }

    /// Convert to a UIElement for use as content in other containers.
    pub fn as_uielement(&self) -> XamlUIElement {
        let handle = unsafe { ffi::xaml_radiobutton_as_uielement(self.handle) };
        XamlUIElement { handle }
    }
}

impl Drop for XamlRadioButton {
    fn drop(&mut self) {
        unsafe {
            ffi::xaml_radiobutton_destroy(self.handle);
        }
    }
}

unsafe impl Send for XamlRadioButton {}
unsafe impl Sync for XamlRadioButton {}

// ===== Image =====

/// Stretch modes for Image control.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageStretch {
    /// No stretching.
    None = 0,
    /// Fill the available space.
    Fill = 1,
    /// Uniform scaling to fit.
    Uniform = 2,
    /// Uniform scaling to fill.
    UniformToFill = 3,
}

/// A WinRT Image control for displaying images.
pub struct XamlImage {
    handle: ffi::XamlImageHandle,
}

impl XamlImage {
    /// Create a new Image.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_image_create() };
        if handle.0.is_null() {
            return Err(Error::control_creation("Failed to create Image".to_string()));
        }
        Ok(XamlImage { handle })
    }

    /// Set the image source from a URI.
    ///
    /// # Examples
    /// ```no_run
    /// # use winrt_xaml::xaml_native::XamlImage;
    /// let image = XamlImage::new()?;
    /// image.set_source("ms-appx:///Assets/logo.png")?;
    /// image.set_source("https://example.com/image.jpg")?;
    /// # Ok::<(), winrt_xaml::Error>(())
    /// ```
    pub fn set_source(&self, uri: impl AsRef<str>) -> Result<()> {
        let uri_wide = to_wide_string(uri.as_ref());
        let result = unsafe { ffi::xaml_image_set_source(self.handle, uri_wide.as_ptr()) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set image source".to_string()));
        }
        Ok(())
    }

    /// Set the stretch mode for the image.
    pub fn set_stretch(&self, stretch: ImageStretch) -> Result<()> {
        let result = unsafe { ffi::xaml_image_set_stretch(self.handle, stretch as i32) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set image stretch".to_string()));
        }
        Ok(())
    }

    /// Set the size of the image.
    pub fn set_size(&self, width: f64, height: f64) -> Result<()> {
        let result = unsafe { ffi::xaml_image_set_size(self.handle, width, height) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set image size".to_string()));
        }
        Ok(())
    }

    /// Convert to a UIElement for use as content in other containers.
    pub fn as_uielement(&self) -> XamlUIElement {
        let handle = unsafe { ffi::xaml_image_as_uielement(self.handle) };
        XamlUIElement { handle }
    }
}

impl Drop for XamlImage {
    fn drop(&mut self) {
        unsafe {
            ffi::xaml_image_destroy(self.handle);
        }
    }
}

unsafe impl Send for XamlImage {}
unsafe impl Sync for XamlImage {}

// ===== ListView =====

/// Selection modes for ListView control.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ListViewSelectionMode {
    /// No selection allowed.
    None = 0,
    /// Single item selection.
    Single = 1,
    /// Multiple item selection.
    Multiple = 2,
    /// Extended selection (Ctrl/Shift).
    Extended = 3,
}

/// A WinRT ListView control for displaying lists of items.
pub struct XamlListView {
    handle: ffi::XamlListViewHandle,
}

impl XamlListView {
    /// Create a new ListView.
    pub fn new() -> Result<Self> {
        let handle = unsafe { ffi::xaml_listview_create() };
        if handle.0.is_null() {
            return Err(Error::control_creation("Failed to create ListView".to_string()));
        }
        Ok(XamlListView { handle })
    }

    /// Add an item to the list.
    pub fn add_item(&self, item: impl AsRef<str>) -> Result<()> {
        let item_wide = to_wide_string(item.as_ref());
        let result = unsafe { ffi::xaml_listview_add_item(self.handle, item_wide.as_ptr()) };
        if result != 0 {
            return Err(Error::control_creation("Failed to add listview item".to_string()));
        }
        Ok(())
    }

    /// Remove an item at the specified index.
    pub fn remove_item(&self, index: i32) -> Result<()> {
        let result = unsafe { ffi::xaml_listview_remove_item(self.handle, index) };
        if result != 0 {
            return Err(Error::invalid_operation("Failed to remove listview item".to_string()));
        }
        Ok(())
    }

    /// Clear all items from the list.
    pub fn clear(&self) -> Result<()> {
        let result = unsafe { ffi::xaml_listview_clear_items(self.handle) };
        if result != 0 {
            return Err(Error::control_creation("Failed to clear listview items".to_string()));
        }
        Ok(())
    }

    /// Get the number of items in the list.
    pub fn item_count(&self) -> i32 {
        unsafe { ffi::xaml_listview_get_item_count(self.handle) }
    }

    /// Get the currently selected index (-1 if none selected).
    pub fn selected_index(&self) -> i32 {
        unsafe { ffi::xaml_listview_get_selected_index(self.handle) }
    }

    /// Set the selected index.
    pub fn set_selected_index(&self, index: i32) -> Result<()> {
        let result = unsafe { ffi::xaml_listview_set_selected_index(self.handle, index) };
        if result != 0 {
            return Err(Error::invalid_operation("Failed to set listview selected index".to_string()));
        }
        Ok(())
    }

    /// Get the item text at the specified index.
    pub fn get_item(&self, index: i32) -> Result<String> {
        const BUFFER_SIZE: i32 = 1024;
        let mut buffer: Vec<u16> = vec![0; BUFFER_SIZE as usize];

        let result = unsafe {
            ffi::xaml_listview_get_item(self.handle, index, buffer.as_mut_ptr(), BUFFER_SIZE)
        };

        if result < 0 {
            return Err(Error::invalid_operation("Failed to get listview item".to_string()));
        }

        let len = result as usize;
        let text = String::from_utf16_lossy(&buffer[..len]);
        Ok(text)
    }

    /// Register a callback for when the selection changes.
    pub fn on_selection_changed<F>(&self, callback: F) -> Result<()>
    where
        F: Fn(i32) + Send + Sync + 'static,
    {
        let boxed = Box::new(callback);
        let ptr = Box::into_raw(boxed);

        extern "C" fn trampoline<F>(index: i32, user_data: *mut std::ffi::c_void)
        where
            F: Fn(i32) + Send + Sync + 'static,
        {
            unsafe {
                let callback = &*(user_data as *const F);
                callback(index);
            }
        }

        unsafe {
            ffi::xaml_listview_on_selection_changed(
                self.handle,
                std::mem::transmute(trampoline::<F> as *const ())
            );
        }

        std::mem::forget(ptr);
        Ok(())
    }

    /// Set the selection mode.
    pub fn set_selection_mode(&self, mode: ListViewSelectionMode) -> Result<()> {
        let result = unsafe { ffi::xaml_listview_set_selection_mode(self.handle, mode as i32) };
        if result != 0 {
            return Err(Error::control_creation("Failed to set listview selection mode".to_string()));
        }
        Ok(())
    }

    /// Convert to a UIElement for use as content in other containers.
    pub fn as_uielement(&self) -> XamlUIElement {
        let handle = unsafe { ffi::xaml_listview_as_uielement(self.handle) };
        XamlUIElement { handle }
    }
}

impl Drop for XamlListView {
    fn drop(&mut self) {
        unsafe {
            ffi::xaml_listview_destroy(self.handle);
        }
    }
}

unsafe impl Send for XamlListView {}
unsafe impl Sync for XamlListView {}