WPF ListBox MVVM scrollintoview via behavior

 public class ListBoxAutoScrollBehavior:Behavior<ListBox>
 {
     protected override void OnAttached()
     {
         base.OnAttached();
         AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged;
     }

     private void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
     {
         if(sender is ListBox lbx && lbx.SelectedItem!=null)
         {
             lbx.ScrollIntoView(lbx.SelectedItem);
         }
     }

     protected override void OnDetaching()
     {
         AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged;
     }
 }





 <ListBox x:Name="lbx" 
          ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
          SelectedIndex="{Binding SelectedIdx,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
          VirtualizingPanel.IsContainerVirtualizable="True"
          VirtualizingPanel.IsVirtualizing="True"
          VirtualizingPanel.CacheLength="1"
          VirtualizingPanel.CacheLengthUnit="Item"
          >
     <behavior:Interaction.Behaviors>
         <local:ListBoxAutoScrollBehavior/>
     </behavior:Interaction.Behaviors>
     <ListBox.ItemTemplate>
         <DataTemplate>
             <Border
                 Width="{Binding ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"
                 Height="{Binding ActualHeight,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}" >
                 <Border.Background>
                     <ImageBrush ImageSource="{Binding ImgSource}" 
                                 RenderOptions.BitmapScalingMode="Fant"
                                 Stretch="Uniform"/>
                 </Border.Background>
                 <TextBlock Text="{Binding ISBN}"
                            FontSize="50"
                            Foreground="Red"
                            HorizontalAlignment="Center"
                            VerticalAlignment="Center"/>
             </Border>
         </DataTemplate>
     </ListBox.ItemTemplate>
 </ListBox>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2024-11-05 22:57  FredGrit  阅读(6)  评论(0编辑  收藏  举报