C# WINDOWS MAUI專案 使用 xaml & code 動態配置(增加) UI元件
C# WINDOWS MAUI專案 使用 xaml & code 動態配置(增加) UI元件
資料來源: https://learn.microsoft.com/zh-tw/dotnet/maui/user-interface/layouts/grid
https://www.youtube.com/watch?v=yM7opXlu-MU
GITHUB: https://github.com/jash-git/MAUI_WinAPI_Object_test/tree/main/Code/12
GridPage.xaml code
<?xml version="1.0" encoding="utf-8" ?> <mct:Popup xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:mct="clr-namespace:CommunityToolkit.Maui.Views;assembly=CommunityToolkit.Maui" x:Class="MAUI_WinAPI_Object_test.Views.GridPage" CanBeDismissedByTappingOutsideOfPopup="True"> <Grid x:Name="FullGrid" Margin="3" VerticalOptions="Fill" HorizontalOptions="Fill" /> </mct:Popup>
GridPage.xaml.cs code
using CommunityToolkit.Maui.Views; namespace MAUI_WinAPI_Object_test.Views; public partial class GridPage : Popup //: ContentPage { public GridPage() { InitializeComponent(); // 創建一個 Grid 佈局 var grid = FullGrid; grid.BackgroundColor = Colors.AliceBlue; // 定義列和行 grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); // 在網格中添加控制項 var label1 = new Label { Text = "第一行,第一列" }; var label2 = new Label { Text = "第二行,第一列" }; var label3 = new Label { Text = "第一行,第二列" }; var label4 = new Label { Text = "第二行,第二列" }; grid.Add(label1, 0, 0); grid.Add(label2, 1, 0); grid.Add(label3, 0, 1); grid.Add(label4, 1, 1); } }
One thought on “C# WINDOWS MAUI專案 使用 xaml & code 動態配置(增加) UI元件”
C# WINDOWS MAUI專案 在執行階段載入 XAML 動態增加新頁面/新配置
https://learn.microsoft.com/zh-tw/dotnet/maui/xaml/runtime-load?view=net-maui-8.0
在執行階段載入 XAML [在既有配置上使用XAML新增元件]
string navigationButtonXAML = "";
Button navigationButton = new Button().LoadFromXaml(navigationButtonXAML);
...
stackLayout.Add(navigationButton);
在執行階段載入 XAML [新增新頁面]
// See the sample for the full XAML string
string pageXAML = "\r\n\n";
ContentPage page = new ContentPage().LoadFromXaml(pageXAML);
await Navigation.PushAsync(page);
在執行階段載入 XAML [新增新頁面 & 指定元件進行設定]
string pageXAML = "\r\n\n\n\n\n";
ContentPage page = new ContentPage().LoadFromXaml(pageXAML);
Label monkeyLabel = page.FindByName("monkeyName");
monkeyLabel.Text = "Seated Monkey";