Below is an mcve (to reproduce the problem it has to be datatemplated unloadable view).
xaml:
<Window Content="{Binding}" ... >
<Window.Resources>
<DataTemplate DataType="{x:Type local:ViewModel}">
<ListView ItemsSource="{Binding Items}"
SelectionChanged="ListView_SelectionChanged"
Unloaded="ListView_Unloaded"
MouseRightButtonDown="ListView_MouseRightButtonDown">
</ListView>
</DataTemplate>
</Window.Resources>
</Window>
cs:
public class ViewModel
{
public ObservableCollection<string> Items { get; set; } = new ObservableCollection<string>(new[] { "1", "2", "3" });
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e) => Title += "S";
void ListView_Unloaded(object sender, RoutedEventArgs e) => Title += "U";
void ListView_MouseRightButtonDown(object sender, MouseButtonEventArgs e) => DataContext = null;
}
Start program, select item in the list ("S"
will be added to title), right click inside list -> "SU"
will be added to title.
Question: why SelectionChanged
is called when view (ListView
) is unloaded??
Right-clicking without selecting anything will add only "U"
to the tittle.
Simply closing software (disregarding selection) will not cause SelectionChanged
(tested by setting breakpoint).
I will have some logic in SelectionChanged
event and I don't want it to run when view is unloaded, it's unexpected behavior what SelectionChanged
event is called in this case at all.