0

I am using MVVM for my WPF form and now I want to close the new Dialog that I made when a user presses the Cancel button. The cancel button is part of a seperate XAML that gets used around multiple forms. (similar to scripts in javascript)

this is what I have so far:

private void CloseDialogView(object sender)
    {
        var currentElement = (DependencyObject)sender;
        List<object> windowTypes = new List<object>() {
         typeof(fooDialogView), 
         typeof(barDialogView), 
         typeof(foobarDialogView) };
        Type elementType;

        do
        {
            var parent = VisualTreeHelper.GetParent(currentElement);
            currentElement = parent;
            elementType = (currentElement.GetType());
        }
        while (!windowTypes.Contains(elementType));

        foreach (var type in windowTypes)
            try
            {
                var Window = (type.GetType())currentElement;
                Window.Close();
            }
            catch
            { }
    }

in the do-while I just pass through all the elements in the form untill I hit the element that is the window.

In the foreach I want to check if it is one of the windowtypes (Xaml-forms) and if it is, cast that type to the 'currentElement' and then close it.

It does work if I just do

var Window = (fooDialogView)currentElement;
Window.Close();

but I want to avoid having to manually enter each seperate form-name.

  • 1
    Have your forms anything in common? Then you could exctract a common base-class/interface and cast to that instead of the concrete class. – MakePeaceGreatAgain May 23 '18 at 13:15
  • The only things those forms/prompts have in common are their parent-form that summons them and the controls wherein this code is. – Dennis Van Hout May 23 '18 at 13:17
  • mvvm approach - https://stackoverflow.com/questions/3801681/good-or-bad-practice-for-dialogs-in-wpf-with-mvvm – blindmeis May 23 '18 at 13:39

1 Answers1

0

Someone posted the answer

var Window = (Window)sender;
Window.Close();

but it turned out all I needed was

var Window = (Window)currentElement;
Window.Close();

right after the do-while, no need for the foreach-loop. thanks for the swift help :)