A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
Hello,
There is no API in MAUI to load XAML at runtime.
For dynamically loading and modifying control styles, the solution given by MAUI is dynamic styles.
Please refer to the following sample code that modifies a button at runtime using dynamic styles.
Step 1. Define styles in ResourceDictionary:
<Application.Resources>
<ResourceDictionary>
<Style x:Key="RedButtonStyle"
TargetType="Button">
<Setter Property="BackgroundColor" Value="Red" />
</Style>
<Style x:Key="GreenButtonStyle"
TargetType="Button">
<Setter Property="BackgroundColor" Value="Green" />
</Style>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Styles/Colors.xaml" />
<ResourceDictionary Source="Resources/Styles/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Step 2. Use dynamic styles in controls:
<Button Text="test" Style="{DynamicResource RedButtonStyle}" Clicked="Button_Clicked"></Button>
Step 3. Modify styles dynamically:
private void Button_Clicked(object sender, EventArgs e)
{
var btn = sender as Microsoft.Maui.Controls.Button;
if (btn != null)
{
App.Current.Resources["RedButtonStyle"] = App.Current.Resources["GreenButtonStyle"];
}
}
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.