Sergiu
Sergiu

Reputation: 297

wpf window event continue raise after window is closed

I have a problem with wpf events. In the xaml I have following combobox with selectionchanged event:

<ComboBox Grid.Column="1" Grid.Row="1" Name ="comboBox"
          SelectedItem="{Binding CurrentEventBinding.ControlId, ValidatesOnDataErrors=True}"
          ItemsSource="{Binding ControlsNames}" SelectionChanged="ComboboxSelectionChanged">

In the codebehind I have following code:

private void ComboboxSelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
      (DataContext as EventBindingEditViewModel).VmCommands.UpdateSourceCommand.Execute(null);
  }

And I have the following working scenario: Window.ShowDialog(); -> ComboboxSelectedChanged (the event is raised) -> CloseWindow(); Then again: Window.ShowDialog(); -> ComboboxSelectedChanged (the event is raised twice) And if in the immediate window I write sender.GetHashCode() it returns first time the hashcode for the combobox from current window, and at the second time it returns the hashcode of the 'died' window. So the event is raised so many times as the window is showed. It looks like old comboboxes aren't disposed or something like that. Hope you understand my problem. Thanks in advance!

Upvotes: 4

Views: 1597

Answers (2)

Alexandru Dicu
Alexandru Dicu

Reputation: 1235

Give the combobox a name and subscribe to SelectionChanged from code instead of XAML. On Window closing, unsubscribe from the event to make sure that it get's disposed.

<ComboBox Name="MyComboBox"....... />

And then in code:

protected override void OnSourceInitialized(EventArgs e)
{
    MyComboBox.SelectionChanged += ComboBoxSelectionChanged;
}

protected override void OnClosing(CancelEventArgs e)
{
    MyComboBox.SelectionChanged -= ComboBoxSelectionChanged;
}

Do you create the window with new Window() everytime, or it is a singleton ? Make sure to unsubscribe in the same manner from all events that you subscribed. Otherwise, the window that you close will never be disposed.

Upvotes: 1

Alex Butenko
Alex Butenko

Reputation: 3774

The cause is that you are using binding, and it's still working after window closing. Then you change selected item in one window, it's changing selected item in other window (which is closed) via bindings. To resolve this, you should set DataContext = null in closed window. Or you can use the same window every time, just not close it, but hide.

Upvotes: 4

Related Questions