1

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?

Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
c_str
  • 369
  • 1
  • 4
  • 14

2 Answers2

4

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

Mark Hall
  • 53,938
  • 9
  • 94
  • 111
Sivasubramanian
  • 935
  • 7
  • 22
  • -1 don't use procedural code to create or manipulate UI elements in WPF. That's what XAML is for. – Federico Berasategui Jul 08 '14 at 19:07
  • 2
    +1 Using procedural code when OP explicitly asks for it. – Troels Larsen Jul 08 '14 at 19:08
  • Say what you want, however when the OP comes back with a bunch of horrible winforms-like hacks and none of them work at all in WPF, it's going to be **my** advice that saves the OP's ass ;) – Federico Berasategui Jul 08 '14 at 19:09
  • Hi HighScore I do agree with you but as per OP's question ""Is there a way to add a control like in Win Forms C#"" I gave the solution. You would probably put a down vote for the question and not for the answer. – Sivasubramanian Jul 08 '14 at 19:11
  • 1
    @HighCore: If he manages to build an entire WPF application using only procedural code without noticing XAML, somehow I think the rest of the code won't be too shabby either. :) – Troels Larsen Jul 08 '14 at 19:12
  • 1
    Yes, I don't want to use XAML. I requested for C# Code. omg, thanks ~ It worked! Just changed some of the background stuff to the panel. It works nice now! Thanks! :3 @Sivasubramanian – c_str Jul 08 '14 at 19:14
  • @Sivasubramanian removed the downvote as per your last edit. +1. – Federico Berasategui Jul 08 '14 at 19:16
  • @HighCore Yes. I love raw codes. XAML is as easy as to drag and drop a control to the visual editor. What's the point of it? I mean, it's faster and easy but what sense it has if you don't understand how the program manages to create a control by drag and drop it from toolbox. I do it for learning, and it's MY WAY to learn and code. I always do everything in clean code. I never liked the drag and drop control from toolbox :/ That's not funny. I like to break my head reading all my code :D – c_str Jul 08 '14 at 19:18
  • @user3576526 you are welcome. :) But XAML is the backbone of WPF, so you cannot simply avoid it. :) – Sivasubramanian Jul 08 '14 at 19:19
  • @user3576526 fyi, WPF does NOT generate procedural code from the XAML you create (either manually typing or with a designer). It uses a XAML Parser to instantiate the object graph from XAML at runtime. – Federico Berasategui Jul 08 '14 at 19:23
  • 1
    @HighScore : My friend used to say there is one guy in SO who used to curse WinForms and praise WPF. I suspect you are the guy he is talking about. Dude you are famous in SO. :) – Sivasubramanian Jul 08 '14 at 19:29
  • Well I don't want to make a discussion. I like it because it's funny for me and I like to know everything about the procedural code. I like to make it work by deep inside! It's my way! You can't just change my way of doing things because "it's not efficient or not enchances the full experience of a WPF in XAML". I asked for a simple question and he gave me a simple answer. That's all, I like your advice but this is getting out of the main question I did lol @HighCore – c_str Jul 08 '14 at 19:34
  • @user3576526 if you want to get "deep knowledge" as you say, then read about [Data Binding](http://msdn.microsoft.com/en-us/library/ms752347(v=vs.110).aspx) and [Data Templating](http://msdn.microsoft.com/en-us/library/ms742521(v=vs.110).aspx) in MSDN. WPF is NOT winforms. Do as you wish, however when the complexity of the [Visual Tree](http://msdn.microsoft.com/en-us/library/ms753391(v=vs.110).aspx) prevents you from doing things *your* way (rather than the proper way), you'll come back here with another question and the answer's going to be "delete all that horrible code and start all over" – Federico Berasategui Jul 08 '14 at 19:36
  • @user3576526 : I can understand you man, WinForm developers hate XAML initially but as days goes by they will start loving XAML. I like your attitude, you go by your way and you will figure out which is best. – Sivasubramanian Jul 08 '14 at 19:40
  • @Sivasubramanian well I AM a WinForms developer but the only reason I switched to WPF is because I couldn't manage to create a simple transparent textbox. I had a lot of trouble with the WIN32 API methods and the Handle. I just make this program in WPF because it easily supports Background = Brushes.Transparent; and makes a transparent textbox. That's ALL I use WPF LOL – c_str Jul 08 '14 at 19:43
1

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.

Troels Larsen
  • 4,462
  • 2
  • 34
  • 54
  • Ohh thanks, but I didn't know how to make the panel fill the form above so I can add the controls / elements over the form. I understood about creating the panel, just needed to know how to add it to my window to manipulate the form content. Anyways, thanks! :3 – c_str Jul 08 '14 at 19:23
  • @user3576526 you don't "manipulate the form content" in WPF. Read about [DataBinding](http://msdn.microsoft.com/en-us/library/ms752347(v=vs.110).aspx). You're going about this in a totally wrong way. You will hit a really hard wall with your face... – Federico Berasategui Jul 08 '14 at 19:26
  • @TroelsLarsen I disagree with your statement about `dynamic` UIs. If you're doing some kind of dynamic UI where you "add" and "remove" items at runtime, that's what an `ItemsControl` is for. Even in that case, a XAML+DataBinding approach is much preferable rather than a bunch of horrible winforms-like hacks. – Federico Berasategui Jul 08 '14 at 19:32
  • That's right! "Coding everything in the code-behind is the web-design equivalent of sending a blank HTML file and creating everything in JavaScript." I always leae the Viual design in blank because I never use it. I love to create everything line by line x3 – c_str Jul 08 '14 at 19:36
  • @HighCore: That greatly depends on your definition of dynamic. Say that you want to build the UI from an unknown data source, and populate the UI accordingly. Either you generate XAML and compile it at runtime, use FrameworkElementFactory, or simply create and add the controls procedurally. Now that is an extreme case, and I don't really think that is what OP had in mind. I am not a WPF novice either, despite having only recently started using SO :D – Troels Larsen Jul 08 '14 at 19:37
  • @TroelsLarsen `FrameworkElementFactory` - Sorry, NO. reminds me of [this](http://www.codeproject.com/Articles/444371/Creating-WPF-Data-Templates-in-Code-The-Right-Way). And if you have an "unknown data source", then it's a responsibility of the ViewModel to create a proper data structure that can be bound to an `ItemsControl` (again) with proper data templates. No need for winforms hacks. – Federico Berasategui Jul 08 '14 at 19:41
  • @HighCore: If you don't know the properties until runtime, you can't create a 'proper' DataTemplate. You can add PropertyDescriptors to your ViewModel, but you will still need a place to define which properties to show, thus your DataTemplate needs to be dynamic as well. Bringing us back to FrameworkElementFactory or generated XAML. I'm not really argueing against you, I'm just saying that cases exist where procedurally generated UI is not an atrocity. OPs problem is likely not one. – Troels Larsen Jul 08 '14 at 19:47
  • @TroelsLarsen *somewhat* agree on that (very little). I would still find a way not to tie my code to `System.Windows` if I had to do something like that. Even if you don't know the properties, the ViewModel can act as a proxy between the unknown data structure and a well-known established format that can be used for Data Templates. – Federico Berasategui Jul 08 '14 at 19:52
  • @HighCore: I don't understand the part about tieing code to System.Windows. I would never do this is in ViewModel, only in a custom- or user control, which are quite tied there already. Coming from a huge ERP application, where customers are able to create plugins that alter the UI, I can say with some confidence that of all possible way to solve a given problem, procedurally changing the UI is not *always* the worst, and under rare circumstances, actually the least worst. – Troels Larsen Jul 08 '14 at 20:01
  • @TroelsLarsen right. I agree on your last comment, however the `confidence` part is crucial. You can do stuff like that because you `really know` what you're doing, as opposed to 99% of developers I see around who rather than learning the proper way to do things, they just try to use WPF as if it were winforms. – Federico Berasategui Jul 08 '14 at 20:04
  • 1
    @HighCore: Well, doing Techonology X like Technology Y because you *know* Technology Y rarely leads to anything other than a huge refactoring 2-3 years down the line, when you realize the error of your ways :D I appreciate your intentions of trying to save OP at least some of that trouble. – Troels Larsen Jul 08 '14 at 20:07