简体   繁体   中英

How to add controls / Elements to a form in the WPF C# code?

Is there a way to add a control like in Win Forms C# Button b = new Button(); and then add it just like Form1.Controls.Add(b);

I can't do this in WPF because I don't have a Controls attribute in the Window class. How can I do this. I read this of just putting a Panel, dock it to fill and then there I use this:

myPanel.Children.Add(b);

But then it comes to me again. How do I create and add a Panel and dock it to fill?

If I use Panel p = new Panel(); it marks error. And how do I add the panel to my MainWindow?

You can add a stackpanel to window like below.

StackPanel myPanel = new StackPanel();
myWindow.Content = myPanel;

Like @HighCore said below, it is not cleaner to add controls in codebehind. Use XAML wherever it is possible and avoid adding controls in code behind

You can create any structure in C# as you can in XAML.

var p = new Panel();

Above doesn't work because Panel is an abstract class. You can, however do:

var p = new StackPanel();
var g = new Grid();
var wp = new WrapPanel();
var dp = new DockPanel();
//Etc.

See all panels here: http://msdn.microsoft.com/en-us/library/system.windows.controls.panel(v=vs.110).aspx

<Window ...>
    <StackPanel>
        <TextBox/>
    </StackPanel/>
</Window>

is equivalent with (from your MainWindow.xaml.cs):

var sp = new StackPanel();
sp.Children.Add(new TextBox);
Content = sp;

EDIT: Just to be clear, you ONLY want to create your UI in C# if it is dynamic in nature. If you know which fields will be there, always, use XAML. It is the HTML of WPF. Coding everything in the code-behind is the web-design equivalent of sending a blank HTML file and creating everything in JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM