0

I'm trying to close window by clicking the button on another window and getting System.InvalidOperationException: 'The calling thread cannot access this object because a different thread owns it.'

The window I want to close created by the CreateWindow(). It have its closing button, but I want to close this window by clicking on button located on another window also. The button on another window invoke the "ReturnToSearchCommand" and create RelayCommand "ReturnToSearch" where located the code for closing the foreign window.

The code is:

 private void CreateWindow()
        {
            _buttonWindow = new ButtonList();
            var stackPanel = new StackPanel { Orientation = Orientation.Vertical };
            Button _closeButton = new Button();
            _closeButton.Content = "Close";
            _closeButton.Click += new RoutedEventHandler(CloseWindow);
            stackPanel.Children.Add(_closeButton);
            _buttonWindow.Content = stackPanel;
            _buttonWindow.Height = (_companiesDictionary.Keys.Count + 2) * 35;
            _buttonWindow.ShowDialog();
        }
private void CloseWindow(object sender, RoutedEventArgs e)
        {
            _buttonWindow.Close();
        }
public virtual ICommand ReturnToSearchCommand
        {
            get
            {
                return new RelayCommand(ReturnToSearch, delegate () { return true; });
            }
        }
private void ReturnToSearch()
{
    ShowSearchPanel = true;
    PrimaryCategory = null;
    _buttonWindow.Close();
}
Julya Levin
  • 543
  • 1
  • 4
  • 11
  • With `ShowDialog()` IMHO you can't. Use `Show()` instead – Thomas Weller Oct 06 '18 at 20:54
  • When I using Show() the windows creates for a second and disapeares because stack pointer continue running, but with ShowDialog() the stack pointer stays on ShowDialog() line till I manually closing the window , only then it continue. And this is what I need. – Julya Levin Oct 08 '18 at 06:09
  • If it doesn't close itself, the window is not gone. Maybe it's in the background. – Thomas Weller Oct 08 '18 at 11:21
  • You should look into `Dispatcher`. You can read the [MSDN article](https://learn.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatcher?view=netframework-4.7.2) on it, or [this answer](https://stackoverflow.com/questions/7839296/using-the-c-sharp-dispatcher) might help, as well. – DonBoitnott Oct 08 '18 at 13:55
  • @JulyaLevin: How is ButtonList implemented? Are you running the windows pn different threads? – mm8 Oct 08 '18 at 14:14
  • I create buttons object, add every one as stackPanel child. – Julya Levin Oct 08 '18 at 18:20

0 Answers0