从代码隐藏添加 WPF 用户控件 [英] Adding a WPF User Control from Code Behind

查看:31
本文介绍了从代码隐藏添加 WPF 用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UserControl,我想在运行时添加到我当前的 WPF 页面.这可能吗?

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

有一个 Menu-bar 并且在它下面我想拥有我的所有信息,即我选择 Menu ->Show Orders 然后我想在 Menu 下添加 OrderList-UserControl.

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.

当然我可以为此使用 Order WPF 页面,但随后我必须在任何地方重新创建 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.

我尝试过类似这样的东西,它根本没有显示任何内容,它确实运行了 UserControl 中的代码,但我的窗口上没有显示任何内容:

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));

建议?

推荐答案

如果您将 ContentPresenter 作为占位符,您可以将该控件的 Content 属性设置为在代码隐藏中生成的控件.

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

奇怪,看这个链接中的代码 你正在做的事情应该可以正常工作——我给你的代码在我的应用程序中肯定有效——所以我猜你的自定义控件或屏幕重绘有问题.可以直接在XMAL中添加控件看看吗?如果您通过后面的代码添加控件然后强制屏幕重绘(用另一个窗口覆盖然后揭开它)会发生什么.

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).

这篇关于从代码隐藏添加 WPF 用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆