Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf window event continue raise after window is closed

Tags:

wpf

dispose

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!

like image 330
Sergiu Avatar asked Nov 16 '25 21:11

Sergiu


1 Answers

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.

like image 98
Alex Butenko Avatar answered Nov 18 '25 19:11

Alex Butenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!