下面是一个mcve(重现问题,它必须是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;
}
启动程序,在列表中选择项目("S"
将添加到标题中),右键单击列表内部 - &gt; "SU"
将添加到标题中。
问题:为什么在卸载视图(SelectionChanged
)时调用ListView
?
右键单击而不选择任何内容只会将"U"
添加到tittle。
简单地关闭软件(忽略选择)将不导致SelectionChanged
(通过设置断点进行测试)。
我将在SelectionChanged
事件中有一些逻辑,我不希望它在卸载视图时运行,这是意外的行为,在这种情况下调用SelectionChanged
事件。