Filip Ekberg
Filip Ekberg

Reputation: 36327

Adding a WPF User Control from Code Behind

I have a UserControl that I want to add at runtime to my current WPF Page. Is this possible?

Having a Menu-bar and under it i want to have all my information, i.e. that i select Menu -> Show Orders then I want the OrderList-UserControl to be added under the Menu.

Sure I could use an Order WPF Page for that but then I'd have to re-create the Menu everywhere? And I don't like the redundancy in that.

I tried something like this which didn't display anything at all, it sure did run the code inside the UserControl but nothing is displayed on my window:

wrapPanel1.Children.Add(new OrderControl(100));

Suggestions?

Upvotes: 0

Views: 11674

Answers (1)

Martin Harris
Martin Harris

Reputation: 28637

If you put a ContentPresenter as a placeholder you can set the Content property of that control to a control generated in codebehind.


Strange, looking at the code in this link what you are doing should work correctly - and the code I gave you definitely works in my app - so I guess there is something wrong either with your custom control or the screen redraws. Can you add the control directly in XMAL and see it? What happens if you add the control through code behind then force a screen redraw (cover the window with another and then uncover it).

Upvotes: 2

Related Questions