我正在尝试通过单击另一个窗口上的按钮并获得System.InvalidOperationException来关闭窗口:“调用线程无法访问该对象,因为另一个线程拥有它。”
我要关闭的窗口由CreateWindow()创建。它具有关闭按钮,但是我也想通过单击另一个窗口上的按钮来关闭此窗口。另一个窗口上的按钮调用“ ReturnToSearchCommand”,并在用于关闭外部窗口的代码所在的位置创建RelayCommand“ ReturnToSearch”。
代码是:
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();
}