You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 21:01:22