简体   繁体   中英

Custom user control not appearing in WPF window?

I have a custom WPF user control called a TimeoutPanel that I am trying to use. However, if I try to add it to my window from the .cs file, it does not actually show up.

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

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

I am calling it with the following code in the .cs file for a Homescreen window:

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

It crashes with exception: Additional information: Cannot create object of type 'TicketBooth.TimeoutPanel'. CreateInstance failed, which can be caused by not having a public default constructor for 'TicketBooth.TimeoutPanel'. Error at object 'System.Windows.Controls.Grid' in markup file 'TicketBooth;component/homescreen.xaml' Line 174 Position 10.

Thanks!

What you are doing would in no way place that UserControl on the Window of your WPF application. You need to place the UserControl on a child within Window. Setting the Visiblity does not actually place the UserControl as a child of any container.

My guess is that a Grid is your container within the Window. If so; to add your UserControl to the Grid, simply add it as a child within the Grid. 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

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

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