How to create button using only code in Avalonia UI

445 views Asked by At

I created the button using XAML, and i want that this button will make a new one, how to create and display new button using only code?

I guessed to this

var bt = new Button();
bt.Height = 100;
bt.Name = "QWE";

But I IDK what to do next.

1

There are 1 answers

3
Max Katz On BEST ANSWER

You need to add your button to the panel. In Avalonia, different kinds of Panels are used to host one or more controls with different layout rules (stack, grid, wrap...).

Let's say if you had your XAML like this:

<Window ...>
    <Grid>
        <Button Content="QWE" Height="100" />
    </Grid>
</Window>

Grid would be a parent Panel here.

The same XAML can be rewritten to C# code in a similar way:

var window = new Window();
var grid = new Grid();
var button = new Button() { ... };
// adding Button to the Grid Panel as a child
grid.Children.Add(button);
// setting Window content to be a Grid (window can only have a single content child, since it's not a panel)
window.Content = grid;

Or, alternatively, if you need to mix both XAML and C#, you can assign a Name to the Grid:

<Grid x:Name="RootGrid">

And then add button to it from the C# code:

var button = new Button() { ... };
RootGrid.Children.Add(button);

Hope it helps.