简体   繁体   中英

listbox of xaml windows

I create a new Xaml Windows application named Slide with some elements. I want to see list of this Slides instances in listbox element.

List slides = new List();
public void BtnNewSlide_OnClick(object sender, RoutedEventArgs e)
{
    slides.Add(new Slide());
    SlidesList.Items.Clear();
    SlidesList.ItemsSource = slides.ToList();            
}

but I get this error when click on BtnNewSlide :

Window must be the root of the tree. Cannot add Window as a child of Visual.

The error you get is fairly clear. You cannot add a Window as a child of Visual. It must always be on top of the hierarchy. What you could do instead is encapsulate the visuals which are inside the Slide window into an user control and then add the user control instead.

For an example how to create an user control you can take a look here :

http://www.codeproject.com/Articles/32825/How-to-Creating-a-WPF-User-Control-using-it-in-aW

After you created the control you need to move your XAML into it and then simply add the user control to the list instead of adding the Slide window.

Something like this :

List<MyUserControl> slides = new List<MyUserControl>();
public void BtnNewSlide_OnClick(object sender, RoutedEventArgs e)
{
    slides.Add(new MyUserControl());
    SlidesList.Items.Clear();
    SlidesList.ItemsSource = slides;     
}

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