惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
IT之家
IT之家
美团技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell
Y
Y Combinator Blog
T
Tailwind CSS Blog
D
Docker
博客园 - Franky
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Google DeepMind News
Google DeepMind News
腾讯CDC
Vercel News
Vercel News
Engineering at Meta
Engineering at Meta
U
Unit 42
The Cloudflare Blog
S
SegmentFault 最新的问题
WordPress大学
WordPress大学
爱范儿
爱范儿
Recent Announcements
Recent Announcements
博客园 - 聂微东
博客园 - 叶小钗
H
Help Net Security
MyScale Blog
MyScale Blog

博客园 - FredGrit

WPF customize via three combied custom controls WPF DataGrid DataGridTemplateColumn DataTemplate ContentPresenter ContentTemplate WPF Customcontrol NumUpDownScroller WPF CustomControl override Template in Generic.xaml and invoke different style WPF HierarchicalDataTemplate customize via ToggleButton WPF DataGrid DataGridTemplateColumn DataTemplate call predefined DataTemplate via ContentPresenter and ContentTemplate WPF ListBox load data via contentcontrol an ItemTemplate WPF DataGrid load data from Asp.Net Core WebAPI WPF TreeView HierarchicalDataTemplate with grouped Data WPF display grouped data with GroupBox and ItemsControl WPF invoke data from WebAPI,DataGridTemplate call pre defined DataTemplate via ContentPresenter WPF ListBox load data from WCF WPF datagrid load data from WCF via json, export selected items to json file WPF ItemsControl load data from WCF,DataTemplate, ContentControl WPF customize rotated wheel relentlessly via custom control WPF embed DataTemplate in HierchicalDataTemplate of TreeView WPF ContentControl, ItemsControl, ItemsPanelTemplate,VirtualizingStackPanel,convert xml string to List<T> WPF parse web.config recursively, TreeView and HierarchicalDataTemplate WPF Custom control in cs and Generic.xaml WPF ContextMenu independent visual tree resolved via Freezable implemented class WPF custom control GetTemplateChild vs FindName,NameScope separation between Logical Tree and Visual Tree, WPF ListBox ListView Datatemplate, parse xml to List via XmlSerializer and StringReader WPF TreeView HierarchicalDataTemplate, parse xml via traverse in XmlElement WPF parse xml via [XmRoot] and [XmlElement] attributes together, contentcontrol's template is ControlTemplate from Resources WPF ContentControl invoke Template from resource, reuse datatemplate WPF deserialize xml string as List via [XmlRoot] and [XmlElement] attribute WPF ContentControl Template WPF DatagridTemplate Binding DataTemplate WPF TreeView explicitly given key name to HierarchicalDataTemplate WPF, parse XMlDocument as List
WPF two listbox scroll syncchronously via behavior
FredGrit · 2026-08-30 · via 博客园 - FredGrit
Install-Package Microsoft.Xamls.Behavior.WPF
 public class ListBoxSyncScrollBehavior : Behavior<ListBox>
 {
     static Dictionary<string, ScrollViewer> scrollViewerCache = new Dictionary<string, ScrollViewer>();

     public ListBox SourceObj
     {
         get { return (ListBox)GetValue(SourceObjProperty); }
         set { SetValue(SourceObjProperty, value); }
     }

     // Using a DependencyProperty as the backing store for SourceObj.  This enables animation, styling, binding, etc...
     public static readonly DependencyProperty SourceObjProperty =
         DependencyProperty.Register(
             nameof(SourceObj),
             typeof(ListBox),
             typeof(ListBoxSyncScrollBehavior),
             new PropertyMetadata(null));



     protected override void OnAttached()
     {
         base.OnAttached();

         AssociatedObject.Loaded += AssociatedObject_Loaded;
         AssociatedObject.Unloaded += AssociatedObject_Unloaded;
     }

     private void AssociatedObject_Unloaded(object sender, RoutedEventArgs e)
     {
         scrollViewerCache.Clear();
     }

     private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
     {
         if (!scrollViewerCache.ContainsKey(AssociatedObject.Name))
         {
             var scrollViewer = GetScrollViewer(AssociatedObject);
             if (scrollViewer != null)
             {
                 scrollViewer.Name = AssociatedObject.Name;
                 scrollViewerCache.Add(AssociatedObject.Name, scrollViewer);
                 scrollViewer.ScrollChanged += ScrollViewer_ScrollChanged;
             }
         }
     }

     private void ScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
     {
         var srcScrollViewer = sender as ScrollViewer;
         if (srcScrollViewer != null)
         {
             foreach (var de in scrollViewerCache)
             {
                 if (de.Key != srcScrollViewer.Name)
                 {
                     var targetScrollViewer = scrollViewerCache[de.Key] as ScrollViewer;
                     if (targetScrollViewer != null)
                     {
                         targetScrollViewer.ScrollToVerticalOffset(srcScrollViewer.VerticalOffset);
                         targetScrollViewer.ScrollToHorizontalOffset(srcScrollViewer.HorizontalOffset);
                     }
                 }
             }
         }
     }

     protected override void OnDetaching()
     {
         base.OnDetaching();
     }


     private ScrollViewer GetScrollViewer(DependencyObject dpObj)
     {
         int cnt = VisualTreeHelper.GetChildrenCount(dpObj);
         for (int i = 0; i < cnt; i++)
         {
             var obj = VisualTreeHelper.GetChild(dpObj, i);
             if (obj is ScrollViewer scrollViewer)
             {
                 return scrollViewer;
             }
             var result = GetScrollViewer(obj) as ScrollViewer;
             if (result != null)
             {
                 return result;
             }
         }
         return null;
     }
 }
//WPF
<Window x:Class="WpfApp2.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"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="{Binding MainTitle}" WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Window.Resources>
        <Style TargetType="TextBlock" x:Key="TbkStyle">
            <Setter Property="FontSize" Value="30"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="Red"/>
                    <Setter Property="FontWeight" Value="ExtraBold"/>
                </Trigger>
            </Style.Triggers>
        </Style>

        <DataTemplate DataType="{x:Type local:Book}"
                      x:Key="BookDataTemplate">
            <Grid MinHeight="150" Margin="10,50,10,50">
                <Grid.Resources>
                    <Style TargetType="TextBlock" BasedOn="{StaticResource TbkStyle}"/>
                </Grid.Resources>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding Id}" Grid.Row="0" Grid.Column="0"/>
                <TextBlock Text="{Binding Name}" Grid.Row="0" Grid.Column="1"/>
                <TextBlock Text="{Binding Author}" Grid.Row="0" Grid.Column="2"/>
                <TextBlock Text="{Binding CategoryName}" Grid.Row="1" Grid.Column="0"/>
                <TextBlock Text="{Binding Comment}" Grid.Row="1" Grid.Column="1"/>
                <TextBlock Text="{Binding Content}" Grid.Row="1" Grid.Column="2"/>
                <TextBlock Text="{Binding Summary}" Grid.Row="2" Grid.Column="0"/>
                <TextBlock Text="{Binding Title}" Grid.Row="2" Grid.Column="1"/>
                <TextBlock Text="{Binding Topic}" Grid.Row="2" Grid.Column="2"/>
                <TextBlock Text="{Binding ISBN}" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="3"/>
            </Grid>
        </DataTemplate>

    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <!--<ItemsControl  Grid.Column="0" 
                 BorderBrush="LightBlue"
                 BorderThickness="5"
                 ItemsSource="{Binding BksCollection}"
                 VirtualizingPanel.IsVirtualizing="True"
                 VirtualizingPanel.VirtualizationMode="Recycling"
                 VirtualizingPanel.CacheLengthUnit="Item"
                 VirtualizingPanel.CacheLength="5,5">
            <ItemsControl.Template>
                <ControlTemplate TargetType="ItemsControl">
                    <Border>
                        <ScrollViewer>
                            <ItemsPresenter/>
                        </ScrollViewer>
                    </Border>
                </ControlTemplate>
            </ItemsControl.Template>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <VirtualizingStackPanel IsItemsHost="True"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>

            <ItemsControl.ItemTemplate>
                <StaticResource ResourceKey="BookDataTemplate"/>
            </ItemsControl.ItemTemplate>
        </ItemsControl>-->

        <ListBox Grid.Column="0"
                 x:Name="lbx1"
                 BorderBrush="LightCyan"
                 BorderThickness="5"
                 ItemsSource="{Binding BksCollection}"                 
                 VirtualizingPanel.IsVirtualizing="True"
                 VirtualizingPanel.VirtualizationMode="Recycling"
                 VirtualizingPanel.CacheLength="5,5"
                 VirtualizingPanel.CacheLengthUnit="Item"
                 ItemTemplate="{StaticResource BookDataTemplate}"
                 >
            <behavior:Interaction.Behaviors>
                <local:ListBoxSyncScrollBehavior SourceObj="{Binding ElementName=lbx1}"/>
            </behavior:Interaction.Behaviors>
        </ListBox>

        <ListBox Grid.Column="1" 
                 x:Name="lbx2"
                 BorderBrush="LightCyan"
                 BorderThickness="5"
                 ItemsSource="{Binding BksCollection}"                 
                 VirtualizingPanel.IsVirtualizing="True"
                 VirtualizingPanel.VirtualizationMode="Recycling"
                 VirtualizingPanel.CacheLength="5,5"
                 VirtualizingPanel.CacheLengthUnit="Item"
                 ItemTemplate="{StaticResource BookDataTemplate}">
            <behavior:Interaction.Behaviors>
                <local:ListBoxSyncScrollBehavior SourceObj="{Binding ElementName=lbx2}"/>
            </behavior:Interaction.Behaviors>
        </ListBox>
    </Grid>


</Window>

//cs
using System.Collections;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
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 Microsoft.Xaml.Behaviors;
using Newtonsoft.Json;

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

    public class MainVM : INotifyPropertyChanged
    {
        private static HttpClient client = new HttpClient()
        {
            Timeout = TimeSpan.FromHours(1)
        };

        private string url = "http://localhost:5000/api/book/getbooks/";
        private bool isLoading = false;

        public MainVM()
        {
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                _ = LoadDataAsync(1000000);
            }
        }

        private async Task LoadDataAsync(int cnt = 1000000)
        {
            if (isLoading)
            {
                return;
            }
            isLoading = true;

            try
            {
                MainTitle = $"{DateTime.Now},loading...";
                string jsonStr = await client.GetStringAsync($"{url}{cnt}");
                List<Book> bks = JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                if (bks != null && bks.Any())
                {
                    BksCollection = new ObservableCollection<Book>(bks);
                    MainTitle = $"{DateTime.Now},loaded {BksCollection.Count} items,FirstId:{BksCollection.FirstOrDefault()?.Id}," +
                        $"LastId:{BksCollection.LastOrDefault()?.Id}";
                    System.Diagnostics.Debug.WriteLine(MainTitle);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex?.Message);
            }
            finally
            {
                isLoading = false;
            }
        }

        private ObservableCollection<Book> bksCollection;
        public ObservableCollection<Book> BksCollection
        {
            get
            {
                return bksCollection;
            }
            set
            {
                if (value != bksCollection)
                {
                    bksCollection = value;
                    OnPropertyChanged();
                }
            }
        }

        private string mainTitle = $"{DateTime.Now}";
        public string MainTitle
        {
            get
            {
                return mainTitle;
            }
            set
            {
                if (value != mainTitle)
                {
                    mainTitle = value;
                    OnPropertyChanged();
                }
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propName = "")
        {
            var handler = Volatile.Read(ref PropertyChanged);
            if (handler == null)
            {
                return;
            }
            handler(this, new PropertyChangedEventArgs(propName));
        }
    }

    public class Book
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Author { get; set; }
        public string CategoryName { get; set; }
        public string Comment { get; set; }
        public string Content { get; set; }
        public string ISBN { get; set; }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
    }

    public class ListBoxSyncScrollBehavior : Behavior<ListBox>
    {
        static Dictionary<string, ScrollViewer> scrollViewerCache = new Dictionary<string, ScrollViewer>();

        public ListBox SourceObj
        {
            get { return (ListBox)GetValue(SourceObjProperty); }
            set { SetValue(SourceObjProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SourceObj.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SourceObjProperty =
            DependencyProperty.Register(
                nameof(SourceObj),
                typeof(ListBox),
                typeof(ListBoxSyncScrollBehavior),
                new PropertyMetadata(null));



        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.Loaded += AssociatedObject_Loaded;
            AssociatedObject.Unloaded += AssociatedObject_Unloaded;
        }

        private void AssociatedObject_Unloaded(object sender, RoutedEventArgs e)
        {
            scrollViewerCache.Clear();
        }

        private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            if (!scrollViewerCache.ContainsKey(AssociatedObject.Name))
            {
                var scrollViewer = GetScrollViewer(AssociatedObject);
                if (scrollViewer != null)
                {
                    scrollViewer.Name = AssociatedObject.Name;
                    scrollViewerCache.Add(AssociatedObject.Name, scrollViewer);
                    scrollViewer.ScrollChanged += ScrollViewer_ScrollChanged;
                }
            }
        }

        private void ScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            var srcScrollViewer = sender as ScrollViewer;
            if (srcScrollViewer != null)
            {
                foreach (var de in scrollViewerCache)
                {
                    if (de.Key != srcScrollViewer.Name)
                    {
                        var targetScrollViewer = scrollViewerCache[de.Key] as ScrollViewer;
                        if (targetScrollViewer != null)
                        {
                            targetScrollViewer.ScrollToVerticalOffset(srcScrollViewer.VerticalOffset);
                            targetScrollViewer.ScrollToHorizontalOffset(srcScrollViewer.HorizontalOffset);
                        }
                    }
                }
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
        }


        private ScrollViewer GetScrollViewer(DependencyObject dpObj)
        {
            int cnt = VisualTreeHelper.GetChildrenCount(dpObj);
            for (int i = 0; i < cnt; i++)
            {
                var obj = VisualTreeHelper.GetChild(dpObj, i);
                if (obj is ScrollViewer scrollViewer)
                {
                    return scrollViewer;
                }
                var result = GetScrollViewer(obj) as ScrollViewer;
                if (result != null)
                {
                    return result;
                }
            }
            return null;
        }
    }
}

image

image

image