1

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 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

A while of time is passed, but i have an extra question. I have a grid in main window: <Grid x:Name="RootGrid"> Then i create button and add it to grid: var button = new Button() { ... } RootGrid.Children.Add(button); But nothing happens. I found that i can call main window like this: MnWindow.Show(); , and it will be create new window with new button, but i need that button create in already existing window.
RootGrid.Children.Add(button) does update the existing window, if you can get RootGrid on it. Can you add more details?
pastebin.com/75ws8FtT I forgot to say that the function is in the MainWindow class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.