R
R
Ruslan Serg2019-12-10 11:13:35
WPF
Ruslan Serg, 2019-12-10 11:13:35

How can I dynamically create and display buttons in a WPF window?

How to dynamically create and display buttons in a window? The window was created via "Project" - "Add window".
Everywhere it is suggested to use "this.Controls.Add(button)". But:
'MainWindow' does not contain a 'Controls' definition, and no accessible extension method 'Controls' could be found that takes the type 'MainWindow' as the first argument (perhaps a using directive or an assembly reference is missing).
And in general it is not clear what this refers to and where it all happens.

/**********************/
// Открытие окна и генерация кнопок происходит по нажатию кнопку, т.е это событие
            int itemsCount = 5;
            int buttonMargin= 20;
            int left = 10;
            int top = 10;
            for(int i=1; i != itemsCount; i++)//Вывод кнопок в цикле
            {
                System.Windows.Forms.Button button = new System.Windows.Forms.Button(); //Создание кнопки
                button.Left = left;
                button.Name = "TEST";
                button.Top = top + buttonMargin;
                this.Controls.Add(button);//?
                top += button.Height;
            }
Window1 win = new Window1();
win.Show();
/**********************/

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
LiptonOlolo, 2019-12-10
@RuslanSerg

Use ItemsPresenter, override ItemTemplate.
But in general, it's even better to switch to the MVVM pattern and do it all through Binding.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question