How to customize the appearance of the Button using DataTemplate in .NET MAUI (SfButton)?
This section explains how to customize the appearance of the .NET MAUI Button using DataTemplate. This can be achieved by adding your custom view in the Content property. Follow the steps below to implement this:
Step 1: Add DataTempate in XAML
Start by defining the initial and loaded content within a DataTemplate for loading actions. For example, you can add a BusyIndicator and Label to create a loading appearance.
Step 2: Add dynamic DataTemplate update in the cs file
In your cs file, add an event for loading the appearance when you click the button, and update the initial and loaded templates dynamically. The following code sample demonstrates how to apply the busy indicator control as a custom view for a button.
XAML:
<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="loadingTemplate" >
<HorizontalStackLayout>
<busy:SfBusyIndicator x:Name="busy"
AnimationType="CircularMaterial"
IsRunning="True"
WidthRequest="80"
HeightRequest="60"
IndicatorColor="White"
VerticalOptions="Center"
HorizontalOptions="Start"/>
<Label x:Name="label"
Text="Loading..."
FontSize="20"
HorizontalOptions="End"
VerticalOptions="Center"
TextColor="White" />
</HorizontalStackLayout>
</DataTemplate>
<DataTemplate x:Key="initialTemplate">
<Label x:Name="label"
Text="Submit"
FontSize="20"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="White" />
</DataTemplate>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<buttons:SfButton x:Name="button"
Text="Button"
Content="{StaticResource initialTemplate}"
Clicked="button_Clicked"
Background="Orange"
WidthRequest="200"
HeightRequest="50"/>
</ContentPage.Content>
C#:
private void button_Clicked(object sender, EventArgs e)
{
var template = (DataTemplate)Resources["initialTemplate"];
var itemTemplate = (DataTemplate)Resources["loadingTemplate"];
if(button.Content == template)
{
button.Content = itemTemplate;
button.Background = Colors.Gray;
}
else
{
button.Content = template;
button.Background = Colors.Orange;
}
}
Output:
Conclusion
I hope you enjoyed learning how to customize the appearance of the button using DataTemplate in .NET MAUI Button (SfButton).
Refer to our .NET MAUI Button’s feature tour page for other groundbreaking features. You can explore our .NET MAUI Button documentation to understand how to present and manipulate data.
Check out our .NET MAUI components from the License and Downloads page for current customers. If you are new to Syncfusion®, try our 30-day free trial to check out our .NET MAUI Button and other .NET MAUI components.
Please let us know in the following comments section if you have any queries or require clarification. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!