I'm attempting to write a program, part of which will display a list of open windows (or more specifically, their names or titles)
So the XAML for the view looks like this:
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<ItemsControl ItemsSource="{Binding Windows}" />
and the ViewModel
class looks like this:
public ObservableCollection<Window> Windows { get; set; }
public ViewModel()
{
this.Windows = new ObservableCollection<Window>();
this.Windows.Add(new Window());
}
This causes the program (and the designer view) to throw InvalidOperationException: Window must be the root of the tree. Cannot add Window as a child of Visual.
It seems that the problem is that the ItemsControl
thinks I actually want to add the Window
itself as a control rather than as a class (where I would expect the window to show the text System.Windows.Window
or something similar).
I've tried adding <ItemsControl.ItemTemplate><DataTemplate>...
, but this seems to have the same result.
Finally, I've tried creating a dummy WindowHolder
class with a single public property of a Window
. That seems to work, but seems a really inelegant way of doing things where it feels like it should be simpler.
tl;dr
The question is "How can you simply (preferably in XAML) display a list of window titles on a WPF ItemsControl
, bound to an ObservableCollection<Window>
in the view model?