ListBox恢复视图后,未显示项无法取消选中的技术问题咨询
MVVM中ListBox选中状态双向绑定异常问题
将ListBoxItem的IsSelected属性双向绑定到底层模型的IsSelected属性后,当绑定的模型集合过大时,切换至其他用户控件使ListBox失去焦点,再次选中ListBox内的项时,仅屏幕外的项无法被取消选中。

MainView.xaml
<UserControl x:Class="ListBox_Selection_Issue.Views.MainView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:ListBox_Selection_Issue.Views" xmlns:vms="clr-namespace:ListBox_Selection_Issue.ViewModels" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <UserControl.DataContext> <vms:MainViewModel/> </UserControl.DataContext> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <ListBox Grid.Row="0" SelectionMode="Extended" ItemsSource="{Binding FirstCollection}"> <ListBox.ItemContainerStyle> <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" /> </Style> </ListBox.ItemContainerStyle> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <Button Grid.Row="1"/> </Grid> </UserControl>
MainViewModel.cs
using System.Collections.ObjectModel; namespace ListBox_Selection_Issue.ViewModels { class MainViewModel : ObservableObject { private ObservableCollection<CustomClass> _firstCollection; public ObservableCollection<CustomClass> FirstCollection { get { return _firstCollection; } set { _firstCollection = value; OnPropertyChanged("FirstCollection"); } } public MainViewModel() { ObservableCollection<CustomClass> first = new ObservableCollection<CustomClass>(); for (int i = 1; i <= 300; i++) { first.Add(new CustomClass($"{i}")); } FirstCollection = first; } } public class CustomClass { public string Name { get; set; } public bool IsSelected { get; set; } public CustomClass(string name) { Name = name; IsSelected = false; } } }
内容的提问来源于stack exchange,提问作者Trevor Vance
相关产品推荐
相关产品推荐

