Let\'s imagine I have some user control. The user control has some child windows. And user control user wants to close child windows of some type. There is a method in user
I have handled this sort of situation in the past by bringing in the concept of a WindowManager, which is a horrible name for it, so let's pair it with a WindowViewModel, which is only slightly less horrible - but the basic idea is:
public class WindowManager
{
public WindowManager()
{
VisibleWindows = new ObservableCollection();
VisibleWindows.CollectionChanged += OnVisibleWindowsChanged;
}
public ObservableCollection VisibleWindows {get; private set;}
private void OnVisibleWindowsChanged(object sender, NotifyCollectionChangedEventArgs args)
{
// process changes, close any removed windows, open any added windows, etc.
}
}
public class WindowViewModel : INotifyPropertyChanged
{
private bool _isOpen;
private WindowManager _manager;
public WindowViewModel(WindowManager manager)
{
_manager = manager;
}
public bool IsOpen
{
get { return _isOpen; }
set
{
if(_isOpen && !value)
{
_manager.VisibleWindows.Remove(this);
}
if(value && !_isOpen)
{
_manager.VisibleWindows.Add(this);
}
_isOpen = value;
OnPropertyChanged("IsOpen");
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate {};
private void OnPropertyChanged(string name)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
note: I'm just throwing this together very haphazardly; you'd of course want to tune this idea to your specific needs.
But anywho, the basic premise is your commands can work on the WindowViewModel objects, toggle the IsOpen flag appropriately, and the manager class handles opening/closing any new windows. There are dozens of possible ways to do this, but it's worked in a pinch for me in the past (when actually implemented and not tossed together on my phone, that is)