| 1 | using Avalonia; |
| 2 | using Avalonia.Controls; |
| 3 | using Avalonia.VisualTree; |
| 4 | |
| 5 | namespace CascadeIDE.Services; |
| 6 | |
| 7 | /// <summary> |
| 8 | /// Добавить контрол в дерево UI на лету (только Debug). Родитель — Panel по имени. |
| 9 | /// Вызывать из UI-потока. Для ide_add_control. |
| 10 | /// </summary> |
| 11 | public static class UiControlAdd |
| 12 | { |
| 13 | /// <summary>Добавить контрол в конец Children родителя. Возвращает "OK" или сообщение об ошибке.</summary> |
| 14 | public static string AddControl(Visual root, string parentName, string controlType, string? content, string? name) |
| 15 | { |
| 16 | if (string.IsNullOrWhiteSpace(parentName)) |
| 17 | return "Missing parent_name."; |
| 18 | if (string.IsNullOrWhiteSpace(controlType)) |
| 19 | return "Missing control_type."; |
| 20 | |
| 21 | var parent = root is Window mw |
| 22 | ? UiControlAppearance.FindControlByNameAcrossAllWindows(mw, parentName.Trim()) |
| 23 | : UiControlAppearance.FindControlByName(root, parentName.Trim()); |
| 24 | if (parent is null) |
| 25 | return $"Parent not found: {parentName}."; |
| 26 | |
| 27 | if (parent is not Panel panel) |
| 28 | return $"Parent must be a Panel (Grid, StackPanel, DockPanel, etc.), got {parent.GetType().Name}."; |
| 29 | |
| 30 | var control = CreateControl(controlType.Trim(), content ?? "", name?.Trim()); |
| 31 | if (control is null) |
| 32 | return $"Unknown control_type: {controlType}. Use Button, TextBlock, or Border."; |
| 33 | |
| 34 | panel.Children.Add(control); |
| 35 | return "OK"; |
| 36 | } |
| 37 | |
| 38 | private static Control? CreateControl(string controlType, string content, string? name) |
| 39 | { |
| 40 | Control? c = controlType switch |
| 41 | { |
| 42 | "Button" => new Button { Content = content }, |
| 43 | "TextBlock" => new TextBlock { Text = content }, |
| 44 | "Border" => new Border { Child = new TextBlock { Text = content } }, |
| 45 | _ => null |
| 46 | }; |
| 47 | if (c is null) |
| 48 | return null; |
| 49 | if (!string.IsNullOrEmpty(name) && c is StyledElement se) |
| 50 | se.Name = name; |
| 51 | return c; |
| 52 | } |
| 53 | } |
| 54 | |