首页 > 其他分享 >WPF ListBox IsSynchronizedWithCurrentItem True ScrollIntoView via behavior CallMethodAction in MVVM

WPF ListBox IsSynchronizedWithCurrentItem True ScrollIntoView via behavior CallMethodAction in MVVM

时间:2024-10-05 21:14:23浏览次数:10  
标签:CallMethodAction via MVVM Windows imgsList System using null public

 <ListBox Grid.Column="0"
          ItemContainerStyle="{StaticResource lbxItemContainerStyle}"
          ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
          IsSynchronizedWithCurrentItem="True"
          DisplayMemberPath="Id">
     <behavior:Interaction.Triggers>
         <behavior:EventTrigger EventName="SelectionChanged">
             <behavior:CallMethodAction MethodName="ListBox_SelectionChanged" TargetObject="{Binding}"/>
         </behavior:EventTrigger>
     </behavior:Interaction.Triggers>
 </ListBox>


//cs
public void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var lbx=sender as ListBox;
    if(lbx!=null)
    {
        if(e!=null && e.AddedItems!=null && e.AddedItems.Count>0)
        {
            var bk = e.AddedItems[0] as Book;
            if(bk!=null)
            {
                lbx.ScrollIntoView(bk);
            }
        }
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

//xaml
<Window x:Class="WpfApp13.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
        WindowState="Maximized"
        xmlns:local="clr-namespace:WpfApp13"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:BookVM/>
    </Window.DataContext>
    <Window.Resources>
        <Style x:Key="lbxItemContainerStyle" TargetType="ListBoxItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Border Name="_Border"
                                Padding="2"
                                SnapsToDevicePixels="true">
                            <ContentPresenter />
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsSelected" Value="true">
                                <Setter TargetName="_Border" Property="Background" Value="Red"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ListBox Grid.Column="0"
                 ItemContainerStyle="{StaticResource lbxItemContainerStyle}"
                 ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 IsSynchronizedWithCurrentItem="True"
                 DisplayMemberPath="Id">
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="SelectionChanged">
                    <behavior:CallMethodAction MethodName="ListBox_SelectionChanged" TargetObject="{Binding}"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
        </ListBox>
        <ListBox Grid.Column="1"
                 ItemContainerStyle="{StaticResource lbxItemContainerStyle}"
                 ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 IsSynchronizedWithCurrentItem="True"
                 DisplayMemberPath="Name">
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="SelectionChanged">
                    <behavior:CallMethodAction MethodName="ListBox_SelectionChanged" TargetObject="{Binding}"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
        </ListBox>

        <ListBox Grid.Column="2"
                 ItemContainerStyle="{StaticResource lbxItemContainerStyle}"
                 ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 IsSynchronizedWithCurrentItem="True">
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="SelectionChanged">
                    <behavior:CallMethodAction MethodName="ListBox_SelectionChanged" TargetObject="{Binding}"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Image Source="{Binding DataContext.ImgUrl,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}}}"
                           Width="20"
                           Height="50" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>





//cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

namespace WpfApp13
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

       
    }


    public class BooksData:List<Book>
    {
        public BooksData()
        {
            var imgsList = new List<string>(Directory.GetFiles(@"../../Images"));
            if (imgsList != null && imgsList.Any())
            {
                int imgsCount=imgsList.Count;
                for(int i=0;i<100000;i++)
                {
                    Add(new Book()
                    {
                        Id = i + 1,
                        Name = $"Name_{i + 1}",
                        ImgUrl = $"{imgsList[i % imgsCount]}"
                    });
                }
            }
        }
    }

    public class BookVM : INotifyPropertyChanged
    {
        public BookVM()
        {
            InitData();
        }

        private void InitData()
        {
            var imgsList = new List<string>(Directory.GetFiles(@"../../Images"));
            if(imgsList!=null && imgsList.Any())
            {
                int imgsCount=imgsList.Count;
                BooksCollection = new ObservableCollection<Book>();
                for(int i=0;i<10000;i++)
                {
                    BooksCollection.Add(new Book()
                    {
                        Id=i+1,
                        Name=$"Name_{i+1}",
                        ImgUrl = $"{imgsList[i%imgsCount]}"
                    });
                }
            }
        }

        public void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var lbx=sender as ListBox;
            if(lbx!=null)
            {
                if(e!=null && e.AddedItems!=null && e.AddedItems.Count>0)
                {
                    var bk = e.AddedItems[0] as Book;
                    if(bk!=null)
                    {
                        lbx.ScrollIntoView(bk);
                    }
                }
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propName)
        {
            var handler = PropertyChanged;
            if(handler!=null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
        }

        private ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                if(value!=booksCollection)
                {
                    booksCollection = value;
                    OnPropertyChanged(nameof(BooksCollection));
                }
            }
        }
    }

    public class Book
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string ImgUrl { get; set; }
    }
}

 

标签:CallMethodAction,via,MVVM,Windows,imgsList,System,using,null,public
From: https://www.cnblogs.com/Fred1987/p/18448480

相关文章

  • WPF ListBox ListBoxItemTemplate display image automatically via System.Timers.Ti
    //xaml<Windowx:Class="WpfApp6.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.micr......
  • WPF Datagrid display via DataGridTemplateColumn
    <DataGridTemplateColumnHeader="Image"><DataGridTemplateColumn.CellTemplate><DataTemplate><ImageSource="{BindingDataContext.ImgUrl,RelativeSource={RelativeSourceMode=F......
  • WPF image via web url or uri
    Thebasicroadmapistodownloadwebimageatfirst,second convertitintomemeorystream,thirdassignthememorystreamtobitmapimageasStreamSource. //xaml<Windowx:Class="WpfApp2.MainWindow"xmlns="http://schemas.micro......
  • WPF Click Window show XY coordinates in MVVM via InvokeCommandAction of behavior
    1.Install Microsoft.Xaml.Behaviors.Wpf  2.<behavior:Interaction.Triggers><behavior:EventTriggerEventName="MouseDown"><behavior:InvokeCommandActionCommand="{BindingClickCommand}"......
  • WPF MVVM behavior CallMethodAction InvokeCommandAction
    1.Install  Microsoft.Xaml.Behaviors.Wpf 2.xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"<behavior:Interaction.Triggers><behavior:EventTriggerEventName="KeyDown"><behavior:CallMet......
  • WPF MVVM入门系列教程(二、依赖属性)
    说明:本文是介绍WPF中的依赖属性功能,如果对依赖属性已经有了解了,可以浏览后面的文章。 为什么要介绍依赖属性在WPF的数据绑定中,密不可分的就是依赖属性。而MVVM又是跟数据绑定紧密相连的,所以在学习MVVM之前,很有必须先学习一下依赖属性。 依赖属性(DepencencyProperty)是什......
  • Verba - Weaviate RAG 私人助理
    文章目录一、关于Verba什么是Verba?功能列表二、Verba入门安装部署三、API密钥1、Weaviate2、Ollama3、UNSTRUCTURED4、AssemblyAI5、OpenAI6、HuggingFace四、如何使用pip进行部署五、如何从源代码构建六、如何使用Docker安装VerbaVerbaWalkthrough选择您的部署导入......
  • mvvm软件架构 个人见解
    usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceMVVM{  //MVVM框架——Vm层——///  ///主体框架是 数据 ViewModel---》dataservice----》config-----》各个模块  //......
  • WPF Image show picture in high resolution periodically via System.Timers.Timer
    <Windowx:Class="WpfApp411.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft......
  • 论文研读——《RF-Diffusion: Radio Signal Generation via Time-Frequency Diffusion
    本文的是有关无线电信号生成的一篇文章。目录论文简介名词补充现有RF数据生成模型论文贡献RF-Diffusion时频扩散时频扩散——正向销毁过程时频扩散——正向销毁过程时频扩散——逆向恢复过程  时频扩散——条件生成分层扩散Transformer分层扩散Transformer——......