Skip to main content

Creating Basic UI Elements

Avalonia UI provides a rich set of controls and containers for building user interfaces. In this section, we'll explore the fundamental UI elements and how to use them in your applications.

Controls and Containers

Avalonia UI organizes its UI elements into two main categories:

  1. Controls: Interactive elements that users can interact with (buttons, text boxes, etc.)
  2. Containers: Elements that organize and arrange other elements (panels, grids, etc.)

Control Hierarchy

All visual elements in Avalonia UI inherit from a common hierarchy:

  • AvaloniaObject: Base class for all Avalonia objects
    • Visual: Base class for all visual elements
      • Control: Base class for all controls
        • Specific controls (Button, TextBox, etc.)

Types of Controls

Avalonia UI controls can be classified into several types:

  1. Drawn Controls: Generate their own geometry or bitmaps (Border, TextBlock, Image)
  2. Layout Controls: Define the layout of their children (Grid, StackPanel)
  3. Templated Controls: Controls whose visual appearance is defined in a XAML control template (Button, TextBox)

Creating Controls in XAML

To create a control in XAML, you simply add the corresponding element to your XAML file:

<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MyApp.MainWindow"
Title="My Avalonia App">

<Button Content="Click Me" />

</Window>

Creating Controls in Code

You can also create controls programmatically in C#:

// Create a new button programmatically
var button = new Button
{
Content = "Click Me",
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center,
VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center,
Margin = new Avalonia.Thickness(10)
};

// Add the button to a container (assuming myPanel is a Panel control)
myPanel.Children.Add(button);

// Optionally, attach an event handler to the button
button.Click += (sender, e) =>
{
// Handle the button click event
var clickedButton = (Button)sender;
clickedButton.Content = "Clicked!";
};

Text and Input Controls

Text and input controls allow users to view and enter text in your application.

TextBlock

TextBlock is used to display read-only text:

<TextBlock Text="Hello, Avalonia UI!" 
FontSize="24"
FontWeight="Bold"
Foreground="#1E88E5"
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextAlignment="Center"
TextWrapping="Wrap"
Margin="20"
Padding="10"
Background="#E3F2FD"
CornerRadius="4"
Opacity="0.9"
ToolTip.Tip="This is a TextBlock example" />

You can also use inline formatting for rich text:

<TextBlock TextWrapping="Wrap" LineHeight="24" Margin="10">
<Run Text="TextBlock supports " />
<Run Text="bold" FontWeight="Bold" />
<Run Text=", " />
<Run Text="italic" FontStyle="Italic" />
<Run Text=", and " />
<Run Text="colored" Foreground="#E91E63" />
<Run Text=" text. You can also add " />
<LineBreak />
<Run Text="line breaks and " />
<Run Text="different " FontSize="18" />
<Run Text="font " FontSize="22" />
<Run Text="sizes" FontSize="26" />
<Run Text=" within the same TextBlock." />
</TextBlock>

For more complex text formatting, you can use Span elements:

<TextBlock Margin="10">
<TextBlock.Inlines>
<Span>
You can use <Bold>Bold</Bold>, <Italic>Italic</Italic>, and
<Span Foreground="Red">colored</Span> text with Span elements.
</Span>
<LineBreak />
<Span FontFamily="Courier New">
Different font families are also supported.
</Span>
<LineBreak />
<Span TextDecorations="Underline">Underlined text</Span>
<Span> and </Span>
<Span TextDecorations="Strikethrough">strikethrough</Span>
<Span> are available too.</Span>
</TextBlock.Inlines>
</TextBlock>

TextBox

TextBox allows users to enter and edit text:

<TextBox Text="{Binding UserInput}" 
Watermark="Enter text here..."
Width="250"
Height="30"
CornerRadius="4"
BorderThickness="1"
BorderBrush="#BDBDBD"
Padding="8,4"
FontSize="14"
VerticalContentAlignment="Center"
HorizontalAlignment="Left"
Margin="10"
MaxLength="50"
ToolTip.Tip="Enter your text here" />

For a multi-line text box:

<TextBox AcceptsReturn="True"
TextWrapping="Wrap"
Height="100"
Width="300"
Watermark="Enter multiple lines of text..."
ScrollViewer.VerticalScrollBarVisibility="Auto"
FontFamily="Consolas"
Padding="8"
Margin="10" />

For a password field:

<TextBox PasswordChar=""
Watermark="Enter password..."
Width="250"
RevealPassword="False"
Classes="password"
Margin="10" />

Common properties:

  • Text: The text content (often bound to a view model property)
  • Watermark: Placeholder text shown when the TextBox is empty
  • IsReadOnly: Makes the TextBox read-only
  • AcceptsReturn: Allows multi-line input with Enter key
  • PasswordChar: Character to display instead of actual text (for password fields)
  • MaxLength: Maximum number of characters allowed
  • TextWrapping: Controls whether text wraps to a new line
  • SelectionStart/SelectionEnd: Control text selection
  • CaretIndex: Controls the position of the text cursor
  • RevealPassword: When true, shows the password text in a password field

NumericUpDown

NumericUpDown is used for numeric input with increment/decrement buttons:

<NumericUpDown Value="5" 
Minimum="0"
Maximum="10"
Increment="0.5"
FormatString="F1" />

AutoCompleteBox

AutoCompleteBox provides suggestions as the user types:

<AutoCompleteBox Width="200"
Watermark="Search..."
Items="{Binding SearchSuggestions}" />

Buttons and Selection Controls

Buttons and selection controls allow users to perform actions and make selections.

Button

The standard button control:

<Button Content="Click Me" 
Click="OnButtonClick" />

You can also use custom content:

<Button Click="OnButtonClick">
<StackPanel Orientation="Horizontal">
<Image Source="/Assets/icon.png" Width="16" Height="16" />
<TextBlock Text="Click Me" Margin="5,0,0,0" />
</StackPanel>
</Button>

ToggleButton

A button that can be toggled on and off:

<ToggleButton Content="Toggle Me" 
IsChecked="True" />

CheckBox

Used for boolean or three-state selections:

<CheckBox Content="Enable feature" 
IsChecked="True"
IsThreeState="False" />

RadioButton

Used for mutually exclusive selections:

<StackPanel>
<RadioButton Content="Option 1" GroupName="Options" IsChecked="True" />
<RadioButton Content="Option 2" GroupName="Options" />
<RadioButton Content="Option 3" GroupName="Options" />
</StackPanel>

ComboBox

A dropdown list for selecting one item from many:

<ComboBox SelectedIndex="0">
<ComboBoxItem>Option 1</ComboBoxItem>
<ComboBoxItem>Option 2</ComboBoxItem>
<ComboBoxItem>Option 3</ComboBoxItem>
</ComboBox>

With data binding:

<ComboBox Items="{Binding Options}" 
SelectedItem="{Binding SelectedOption}" />

Lists and Data Controls

Lists and data controls are used to display collections of data.

ListBox

Displays a list of selectable items:

<ListBox SelectionMode="Single">
<ListBoxItem>Item 1</ListBoxItem>
<ListBoxItem>Item 2</ListBoxItem>
<ListBoxItem>Item 3</ListBoxItem>
</ListBox>

With data binding:

<ListBox Items="{Binding Items}" 
SelectedItem="{Binding SelectedItem}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

ItemsControl

Displays a collection of items without selection capability:

<ItemsControl Items="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Gray" BorderThickness="1" Margin="2">
<TextBlock Text="{Binding Name}" Padding="5" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

DataGrid

Displays data in a customizable grid:

<DataGrid Items="{Binding People}" 
AutoGenerateColumns="False"
IsReadOnly="True">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridTextColumn Header="Age" Binding="{Binding Age}" />
<DataGridCheckBoxColumn Header="Is Active" Binding="{Binding IsActive}" />
</DataGrid.Columns>
</DataGrid>

TreeView

Displays hierarchical data:

<TreeView Items="{Binding TreeItems}">
<TreeView.ItemTemplate>
<TreeDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}" />
</TreeDataTemplate>
</TreeView.ItemTemplate>
</TreeView>

Common Control Properties

Most Avalonia UI controls share common properties that control their appearance and behavior:

Size and Position

  • Width, Height: Explicit dimensions
  • MinWidth, MinHeight, MaxWidth, MaxHeight: Size constraints
  • Margin: Space around the control
  • HorizontalAlignment, VerticalAlignment: Alignment within parent

Appearance

  • Background: Background color or brush
  • Foreground: Text color or brush
  • BorderBrush, BorderThickness: Border appearance
  • Padding: Space between border and content
  • Opacity: Transparency (0.0 to 1.0)
  • IsVisible: Visibility state

Interaction

  • IsEnabled: Whether the control can be interacted with
  • Focusable: Whether the control can receive keyboard focus
  • ToolTip: Tooltip text or content

Example: Building a Simple Form

Here's an example of a simple form using various Avalonia UI controls:

<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MyApp.MainWindow"
Title="Registration Form"
Width="400" Height="300">

<StackPanel Margin="20">
<TextBlock Text="Registration Form" FontSize="20" FontWeight="Bold" Margin="0,0,0,20" />

<Grid ColumnDefinitions="Auto,*" RowDefinitions="Auto,Auto,Auto,Auto,Auto" VerticalAlignment="Top">
<TextBlock Grid.Row="0" Grid.Column="0" Text="Name:" VerticalAlignment="Center" Margin="0,0,10,10" />
<TextBox Grid.Row="0" Grid.Column="1" Watermark="Enter your name" Margin="0,0,0,10" />

<TextBlock Grid.Row="1" Grid.Column="0" Text="Email:" VerticalAlignment="Center" Margin="0,0,10,10" />
<TextBox Grid.Row="1" Grid.Column="1" Watermark="Enter your email" Margin="0,0,0,10" />

<TextBlock Grid.Row="2" Grid.Column="0" Text="Age:" VerticalAlignment="Center" Margin="0,0,10,10" />
<NumericUpDown Grid.Row="2" Grid.Column="1" Minimum="0" Maximum="120" Value="18" Margin="0,0,0,10" />

<TextBlock Grid.Row="3" Grid.Column="0" Text="Country:" VerticalAlignment="Center" Margin="0,0,10,10" />
<ComboBox Grid.Row="3" Grid.Column="1" SelectedIndex="0" Margin="0,0,0,10">
<ComboBoxItem>United States</ComboBoxItem>
<ComboBoxItem>Canada</ComboBoxItem>
<ComboBoxItem>United Kingdom</ComboBoxItem>
<ComboBoxItem>Australia</ComboBoxItem>
<ComboBoxItem>Other</ComboBoxItem>
</ComboBox>

<TextBlock Grid.Row="4" Grid.Column="0" Text="Interests:" VerticalAlignment="Top" Margin="0,0,10,0" />
<StackPanel Grid.Row="4" Grid.Column="1">
<CheckBox Content="Programming" IsChecked="True" />
<CheckBox Content="Design" />
<CheckBox Content="Gaming" />
<CheckBox Content="Music" />
</StackPanel>
</Grid>

<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,20,0,0">
<Button Content="Cancel" Margin="0,0,10,0" />
<Button Content="Submit" Background="Green" Foreground="White" />
</StackPanel>
</StackPanel>

</Window>

This form includes:

  • Text labels (TextBlock)
  • Text input fields (TextBox)
  • Numeric input (NumericUpDown)
  • Dropdown selection (ComboBox)
  • Checkboxes for multiple selections (CheckBox)
  • Action buttons (Button)
  • Layout containers (StackPanel and Grid)

In the next section, we'll explore layout management in more detail to create more complex and responsive user interfaces.