Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

c# - WPF listbox binding selected only updates items in view

I've been running into a strange issue with a listbox within a UserControl with WPF and MVVM. The listbox has its items bound via a ViewModel and an ObservableCollection<T>, the style property IsSelected is bound to a property Selected inside the individual items.

[...]
<ListBox ItemsSource="{Binding Path=SQLObjects}" FontFamily="Consolas" Margin="5,0,5,5" DisplayMemberPath="Name" SelectionMode="Extended" SelectedItem="{Binding Path=SelectedSQLObject}">
    <ListBox.Resources>
        <Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource MetroListBoxItem}">
            <Setter Property="IsSelected" Value="{Binding Selected, Mode=TwoWay}" />
        </Style>
    </ListBox.Resources>
</ListBox>
[...]

When a user selects a single or multiple items (with ctrl or shift) the properties are updated as expected. But selecting all items with ctrl + a only updates the property Selected of the items visible inside the scroll area of the listbox.

GUI

in the screenshot all items are selected with ctrl + a but only the items currently visible have their property updated. When scrolling down in the listbox without changing the selection, all items are updated as they come into view.

Could this be caused by MahApps.Metro?

The ViewModel is bound to the UserControls Datacontext inside the xaml in the main window.

[...]
<TabItem Header="Trigger">
    <userControls:ObjectControl>
        <userControls:ObjectControl.DataContext>
            <viewmodel:TriggerObjectViewModel DialogCoordinator="{x:Static local:MainWindow.Coordinator}" />
        </userControls:ObjectControl.DataContext>
    </userControls:ObjectControl>
</TabItem>
[...]

All other TabItems use the same usercontrol and have the same issue.

I would like to not use a workaround (e.g. scrolling trought the whole list when the user selects items outside of the current view), is there any kind of property I could set for WPF to update all items inside a collection, regardless if they are visible or not?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I suspect this is due to virtualization. The UI items don't exist until they are scrolled into view.

Try turning off virtualization on your list control:

<ListBox ItemsSource="{Binding Path=SQLObjects}"
         VirtualizingPanel.IsVirtualizing="False">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...