Button Controls in .NET MAUI
Buttons are fundamental UI elements that allow users to trigger an action. .NET MAUI provides a versatile `Button` control with various styling and interaction capabilities.
Basic Button
The simplest form of a button displays text. You can customize its appearance using properties like `BackgroundColor`, `TextColor`, `FontSize`, and `FontAttributes`.
Click Me!
Example XAML:
<Button Text="Click Me" />
Styling Buttons
MAUI buttons can be styled extensively. You can apply styles directly or use `Style` resources for better organization and reusability.
Common Styling Properties:
Text
: The text displayed on the button.BackgroundColor
: The background color of the button.TextColor
: The color of the button's text.BorderColor
: The color of the button's border.BorderWidth
: The width of the button's border.CornerRadius
: Controls the roundness of the button's corners.Padding
: Space between the border and the content.FontAttributes
: Controls bold, italic, or both.FontSize
: The size of the button's text.FontFamily
: The font family for the text.
Styled Button
Example XAML with inline styles:
<Button Text="Custom Styled"
BackgroundColor="#28a745"
TextColor="White"
BorderRadius="20"
BorderWidth="2"
BorderColor="#1e7e34" />
Buttons with Icons
You can include icons alongside text or use icons exclusively. The `ImageSource` property is used for this. MAUI supports various image formats.
Button with Icon
Example XAML for icon button:
<Button ImageSource="your_icon.png" Text="With Icon" />
Button Events
The most common event for a button is `Clicked`, which is raised when the button is tapped or clicked. You can also handle `Pressed` and `Released` events for more granular interaction.
Example C# event handler:
public void OnButtonClicked(object sender, EventArgs e)
{
// Your action here
System.Diagnostics.Debug.WriteLine("Button was clicked!");
}
Example XAML binding to event:
<Button Text="Click Me" Clicked="OnButtonClicked" />
Button States and Interactions
MAUI buttons can visually indicate their state, such as when they are pressed. This can be achieved through styling and event handlers.
Accessibility
Ensure your buttons are accessible by providing meaningful text or an `AutomationProperties.Name` for icon-only buttons.
Example of accessible icon button:
<Button ImageSource="info_icon.png"
AutomationProperties.Name="Information" />
For more advanced customization and detailed API references, please refer to the official .NET MAUI documentation.