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();
}