简体   繁体   English

自定义用户控件没有出现在WPF窗口中?

[英]Custom user control not appearing in WPF window?

I have a custom WPF user control called a TimeoutPanel that I am trying to use. 我有一个尝试使用的自定义WPF用户控件,称为TimeoutPanel。 However, if I try to add it to my window from the .cs file, it does not actually show up. 但是,如果我尝试将其从.cs文件添加到我的窗口中,则它实际上不会显示。

I need to be able to get a handle to the window that owns the timeout screen. 我需要能够获取拥有超时屏幕的窗口的句柄。

TimeoutPanel tp = new TimeoutPanel(this);
tp.Visibility = Visibility.Visible;

I would really appreciate it if someone could please point out what I am doing wrong! 如果有人可以指出我在做什么错,我将不胜感激!

Edit: Here is the constructor for my TimeoutPanel 编辑:这是我的TimeoutPanel的构造函数

public TimeoutPanel(Window parent)
{
    this.InitializeComponent();
    parentWindow = parent;
}

I am calling it with the following code in the .cs file for a Homescreen window: 我在.cs文件的主屏幕窗口中使用以下代码调用它:

TimeoutPanel tp = new TimeoutPanel(this);
MainGrid.Children.Add(tp);

It crashes with exception: Additional information: Cannot create object of type 'TicketBooth.TimeoutPanel'. 发生异常时崩溃:其他信息:无法创建类型为“ TicketBooth.TimeoutPanel”的对象。 CreateInstance failed, which can be caused by not having a public default constructor for 'TicketBooth.TimeoutPanel'. CreateInstance失败,这可能是由于没有“ TicketBooth.TimeoutPanel”的公共默认构造函数造成的。 Error at object 'System.Windows.Controls.Grid' in markup file 'TicketBooth;component/homescreen.xaml' Line 174 Position 10. 标记文件'TicketBooth; component / homescreen.xaml'中的对象'System.Windows.Controls.Grid'错误174行10。

Thanks! 谢谢!

What you are doing would in no way place that UserControl on the Window of your WPF application. 您所做的绝不会将UserControl放在WPF应用程序的窗口中。 You need to place the UserControl on a child within Window. 您需要将UserControl放在Window内的子级上。 Setting the Visiblity does not actually place the UserControl as a child of any container. 设置可见性实际上并不将UserControl放置为任何容器的子级。

My guess is that a Grid is your container within the Window. 我的猜测是,网格是Window内的容器。 If so; 如果是这样的话; to add your UserControl to the Grid, simply add it as a child within the Grid. 要将您的UserControl添加到网格中,只需将其作为子元素添加到网格中即可。 You will need to name your Grid prior to referencing it within the code behind... 您需要先命名网格,然后才能在后面的代码中引用它。

TimeoutPanel tp = new TimeoutPanel(this);
myGrid.Children.Add(tp);

you need to add this control to the some parent control collection. 您需要将此控件添加到某些父控件集合中。

Suppose , you have a stackpanel called stckPanel in your main window so if you want to show this created control under this stack panel , you need to do following code 假设,在主窗口中有一个名为stckPanel的堆栈面板,因此,如果要在此堆栈面板下显示此创建的控件,则需要执行以下代码

TimeoutPanel tp = new TimeoutPanel(this);
stckPanel.Children.Add(tp);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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