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

推荐订阅源

L
LangChain Blog
C
Check Point Blog
博客园 - Franky
V
Visual Studio Blog
云风的 BLOG
云风的 BLOG
aimingoo的专栏
aimingoo的专栏
Microsoft Security Blog
Microsoft Security Blog
V2EX - 技术
V2EX - 技术
AI
AI
Hacker News - Newest:
Hacker News - Newest: "LLM"
Jina AI
Jina AI
S
Security @ Cisco Blogs
Security Archives - TechRepublic
Security Archives - TechRepublic
H
Hacker News: Front Page
H
Hackread – Cybersecurity News, Data Breaches, AI and More
O
OpenAI News
Attack and Defense Labs
Attack and Defense Labs
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
爱范儿
爱范儿
H
Heimdal Security Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
G
Google Developers Blog
G
GRAHAM CLULEY
V
V2EX
The Register - Security
The Register - Security
人人都是产品经理
人人都是产品经理
B
Blog RSS Feed
Schneier on Security
Schneier on Security
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
Help Net Security
Help Net Security
大猫的无限游戏
大猫的无限游戏
C
CERT Recently Published Vulnerability Notes
The GitHub Blog
The GitHub Blog
V
Vulnerabilities – Threatpost
The Last Watchdog
The Last Watchdog
J
Java Code Geeks
S
Secure Thoughts
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
量子位
NISL@THU
NISL@THU
K
Kaspersky official blog
Engineering at Meta
Engineering at Meta
T
Threatpost
Recent Commits to openclaw:main
Recent Commits to openclaw:main
宝玉的分享
宝玉的分享
Security Latest
Security Latest
T
The Exploit Database - CXSecurity.com
博客园_首页
A
Arctic Wolf

博客园 - FredGrit

WPF ContentControl Template is ControlTemplate, ContentTemplate is DataTemplate and must assign value to Content explicitly WPF TreeView show WCF config file WPF itemscontrol loaded downloaded data from WCF via httpclient WPF TreeView HierarchicalDataTemplate DataTemplate, Enum get enum name WPF consume xml generated by WCF , C# deserialize xml to List WPF implemented ICommand and IDisposable WPF ContextMenu,MenuItem command can binding to datacontext's command directly WPF usercontrol pass contextmenu command via implemented Freezable class which does not attach on Visual tree, then invoked in caller MVVM WPF consume data generate by WCF and save via ContextMenu Command in MVVM C# export List<T> to excel file via EPPlus WPF ContextMenu does not rely on host visual tree, the Freezable can exist independently, convey dependency property in usercontrol to caller C# JsonConvert DeserializeObject MissingMemberHandling.Ignore when the source model is completed and the required is partial Freezable objects do not require attachment to the WPF visual tree, maintain a persistent lifetime, and serve as a reliable binding relay between a detached ContextMenu and its parent host control. C# run httplistener to act as service application asynchronously in console, semaphoreslim allow the max concurrent number WPF Microsoft.Xaml.Behaviors.WPF, EventTrigger EventName="PreviewMouseDown" the tunnel event, while the MouseDown can't trigger the command because it was swallowed WPF customize command implemented ICommand, volatile read method is thread safe, preventing cpu and comipler reorder and optimization. WPF ItemsControl load huge 50M+ data WPF consume data generated by WCF periodically in json format WPF customize command based on ICommand and manually trigger WPF consume data generated by grpc services C# produce and consume data via Google.Protobuf WCF produce message and WPF consume periodically via DispatcherTimer WCF deconstruct WebConfig includes bindings, behaviors, service, endpoint ,serviceHostingEnvironment C# insert data into SQLite in batch periodically WPF SQLite SQLiteStudio WPF customize MultiSelectComboBox based on combobox WPF DataGrid Context menu binding command and commandparameter to datacontext WCF set fixed port as http://localhost:8888/ via Project /Properties/web/project url to create virtual directory WPF customize datagrid behavior based on behavior&lt;datagrid&gt; with command and command parameter WPF Microsoft Visual Studio XAML designer is busy WCF WebHttpBinding support both http and https WCF support basicHttpBinding and webHttpBinding - FredGrit WCF TestClient set fixed configuration file WPF consume http json and update periodically via DispatcherTimer WPF Prism.Core version 9.0.537 implemented navigation register singleton with splash screen, pass global variable via RegisterSingleton method WPF render periodically via DispatcherTimer, customize behavior - FredGrit Python cosume WCF service via requests in json format WPF call webHttpBinding from WCF WCF binding webHttpBinding is used to web browser in json format both in request and response WPF invoke WCF dll periodically via DispatcherTimer WCF webHttpBinding is open for web browser and wpf WPF DataTemplateSelector WPF DataGrid customize behavior with multiple commands and command parameters then invoke in mvvm WPF DataGrid behavior customize command and command parameter then invoke and implemented in MVVM WPF ItemsControl customize behavior and save all items WCF service can be accessed by browser WPF WCF produce data as service and WPF consume data as client periodically WPF GRPC and Probuf generated data as service then consume by wpf periodically WPF customize behavior based on Microsoft.Xaml.Behaviors.Wpf with command and commandparameter WPF call data from CPP wrapper dll via CLI\CLR - FredGrit WPF customize behavior WPF get gpu information via System.Management WPF ItemsControl IsItemsHost=True WPF Customize behavior and dependency property command C# Serilog, Serilog.Sinks.Console, Serilog.Sinks.File C# Serilog both in file and console Windows powershell view huge file via command C# serialize huge data more than 100M via splitting into batch and concatenating as one big json file WPF WeakReference C# serialize datetime then deserialize, print lose precision. resolve by ToString(&quot;o&quot;) C# produce data and send via WebSocket as service, Python,Flask,HTML as consumer invoke periodically C# write generated data service and sent via websocket, then consume by python periodically C# DateTime print precision to microseconds C# WebSocket console as service provide data, another console as client,send request periodically C# WebAPI [HttpGet(&quot;{cnt}&quot;] pass argument WPF implement ICommand with async execute WPF ListBox control virtualization in mvvm WPF Data Source invoke from web api C# WebAPI
WPF two separated datagrid scroll synchronously both in horizontal and vertical via behavior
FredGrit · 2026-07-17 · via 博客园 - FredGrit
Install-Package Microsoft.Xaml.Behaviors.Wpf
public class SyncDatagridScrollBehavior : Behavior<DataGrid>
{
    private ScrollViewer _sourceScrollViewer, _targetScrollViewer;
    private bool _isSyncScroll = false;
    public DataGrid TargetDG
    {
        get { return (DataGrid)GetValue(TargetDGProperty); }
        set { SetValue(TargetDGProperty, value); }
    }

    // Using a DependencyProperty as the backing store for TargetDG.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty TargetDGProperty =
        DependencyProperty.Register(nameof(TargetDG),
            typeof(DataGrid),
            typeof(SyncDatagridScrollBehavior),
            new PropertyMetadata(null, OnTargetDGChanged));

    private static void OnTargetDGChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behavior = (SyncDatagridScrollBehavior)d;
        if (behavior != null)
        {
            behavior.RegisterEvents();
        }
    }



    public string BehaviorMainTitle
    {
        get { return (string)GetValue(BehaviorMainTitleProperty); }
        set { SetValue(BehaviorMainTitleProperty, value); }
    }

    // Using a DependencyProperty as the backing store for BehaviorMainTitle.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty BehaviorMainTitleProperty =
        DependencyProperty.Register(
            nameof(BehaviorMainTitle),
            typeof(string), 
            typeof(SyncDatagridScrollBehavior), 
            new PropertyMetadata(null));

    private void RegisterEvents()
    {
        if (TargetDG != null)
        {
            _targetScrollViewer = GetScrollViewer(TargetDG);
            if (_targetScrollViewer != null)
            {
                _targetScrollViewer.ScrollChanged += _targetScrollViewer_ScrollChanged;
            }
        }
    }

    private void _targetScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
    {
        if (_isSyncScroll || _sourceScrollViewer == null)
        {
            return;
        }
        _isSyncScroll = true;
        try
        {
            _sourceScrollViewer.ScrollToVerticalOffset(e.VerticalOffset);
            _sourceScrollViewer.ScrollToHorizontalOffset(e.HorizontalOffset);
            BehaviorMainTitle = $"{DateTime.Now},VerticalOffset:{e.VerticalOffset},HorizontalOffset:{e.HorizontalOffset}";
        }
        finally
        {
            _isSyncScroll = false;
        }
    }

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.Loaded += AssociatedObject_Loaded;
    }

    private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
    {
        _sourceScrollViewer = GetScrollViewer(AssociatedObject);
        if (_sourceScrollViewer != null)
        {
            _sourceScrollViewer.ScrollChanged += _sourceScrollViewer_ScrollChanged;
        }
    }

    private void _sourceScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
    {
        if (_isSyncScroll || _targetScrollViewer == null)
        {
            return;
        }

        _isSyncScroll = true;
        try
        {
            _targetScrollViewer.ScrollToVerticalOffset(e.VerticalOffset);
            _targetScrollViewer.ScrollToHorizontalOffset(e.HorizontalOffset);
            BehaviorMainTitle = $"{DateTime.Now},VerticalOffset:{e.VerticalOffset},HorizontalOffset:{e.HorizontalOffset}";
        }
        finally
        {
            _isSyncScroll = false;
        }
    }

    private ScrollViewer GetScrollViewer(DependencyObject dpObj)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dpObj); i++)
        {
            var child = VisualTreeHelper.GetChild(dpObj, i);
            if (child is ScrollViewer scrollViewer)
            {
                return scrollViewer;
            }

            var result = GetScrollViewer(child);
            if (result != null)
            {
                return result;
            }
        }
        return null;
    }
}



<Window x:Class="WpfApp17.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:WpfApp17"
        mc:Ignorable="d"
        Title="{Binding MainTitle}"
        WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>

    <Window.Resources>
        <Style TargetType="DataGridRow">
            <Setter Property="FontSize" Value="30"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>

        <DataTemplate DataType="{x:Type local:Book}" 
              x:Key="DataGridDataTemplate">
            <DataTemplate.Resources>
                <Style TargetType="TextBlock">
                    <Setter Property="Margin" Value="10,0"/>
                    <Setter Property="FontSize" Value="20"/>
                </Style>
            </DataTemplate.Resources>
            <Border BorderBrush="LightBlue"
            BorderThickness="2"
            Margin="5,0">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Row="0" Grid.Column="0" >Id:<Run Text="{Binding Id}"></Run></TextBlock>
                    <TextBlock Grid.Row="0" Grid.Column="1">Name:<Run Text="{Binding Name}"></Run></TextBlock>
                    <TextBlock Grid.Row="0" Grid.Column="2">ISBN:<Run Text="{Binding ISBN}"></Run></TextBlock>
                    <TextBlock Grid.Row="0" Grid.Column="3">Comment:<Run Text="{Binding Comment}"></Run></TextBlock>
                    <TextBlock Grid.Row="1" Grid.Column="0">Content:<Run Text="{Binding Content}"></Run></TextBlock>
                    <TextBlock Grid.Row="1" Grid.Column="1">Summary:<Run Text="{Binding Summary}"></Run></TextBlock>
                    <TextBlock Grid.Row="1" Grid.Column="2">Title:<Run Text="{Binding Title}"></Run></TextBlock>
                    <TextBlock Grid.Row="1" Grid.Column="3">Topic:<Run Text="{Binding Topic}"></Run></TextBlock>
                </Grid>
            </Border>
        </DataTemplate>
        
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <DataGrid x:Name="LeftDG"
          Grid.Column="0"
          ItemsSource="{Binding Books}"
          VirtualizingPanel.IsVirtualizing="True"
          VirtualizingPanel.VirtualizationMode="Recycling"
          VirtualizingPanel.CacheLength="5,5"
          SnapsToDevicePixels="True"
          UseLayoutRounding="True"
          ScrollViewer.CanContentScroll="True"
          ScrollViewer.IsDeferredScrollingEnabled="False"
          AutoGenerateColumns="False"
          CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <Binding Source="{StaticResource DataGridDataTemplate}"/>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
            <behavior:Interaction.Behaviors>
                <local:SyncDatagridScrollBehavior TargetDG="{Binding ElementName=RightDG}"
                                                  BehaviorMainTitle="{Binding MainTitle,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
            </behavior:Interaction.Behaviors>
        </DataGrid>

        <DataGrid x:Name="RightDG"
              Grid.Column="1"
              ItemsSource="{Binding Books}"
              VirtualizingPanel.IsVirtualizing="True"
              VirtualizingPanel.VirtualizationMode="Recycling"
              VirtualizingPanel.CacheLength="5,5"
              SnapsToDevicePixels="True"
              UseLayoutRounding="True"
              ScrollViewer.CanContentScroll="True"
              ScrollViewer.IsDeferredScrollingEnabled="False"
              AutoGenerateColumns="False"
              CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <Binding Source="{StaticResource DataGridDataTemplate}"/>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
            <behavior:Interaction.Behaviors>
                <local:SyncDatagridScrollBehavior TargetDG="{Binding ElementName=LeftDG}"
                                                  BehaviorMainTitle="{Binding MainTitle,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
            </behavior:Interaction.Behaviors>
        </DataGrid>
    </Grid>
</Window>

image

image

image

image

<Window x:Class="WpfApp17.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:WpfApp17"
        mc:Ignorable="d"
        Title="{Binding MainTitle}"
        WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>

    <Window.Resources>
        <Style TargetType="DataGridRow">
            <Setter Property="FontSize" Value="30"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>

        <DataTemplate DataType="{x:Type local:Book}" 
              x:Key="DataGridDataTemplate">
            <DataTemplate.Resources>
                <Style TargetType="TextBlock">
                    <Setter Property="Margin" Value="10,0"/>
                    <Setter Property="FontSize" Value="20"/>
                </Style>
            </DataTemplate.Resources>
            <Border BorderBrush="LightBlue"
            BorderThickness="2"
            Margin="5,0">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Row="0" Grid.Column="0" >Id:<Run Text="{Binding Id}"></Run></TextBlock>
                    <TextBlock Grid.Row="0" Grid.Column="1">Name:<Run Text="{Binding Name}"></Run></TextBlock>
                    <TextBlock Grid.Row="0" Grid.Column="2">ISBN:<Run Text="{Binding ISBN}"></Run></TextBlock>
                    <TextBlock Grid.Row="0" Grid.Column="3">Comment:<Run Text="{Binding Comment}"></Run></TextBlock>
                    <TextBlock Grid.Row="1" Grid.Column="0">Content:<Run Text="{Binding Content}"></Run></TextBlock>
                    <TextBlock Grid.Row="1" Grid.Column="1">Summary:<Run Text="{Binding Summary}"></Run></TextBlock>
                    <TextBlock Grid.Row="1" Grid.Column="2">Title:<Run Text="{Binding Title}"></Run></TextBlock>
                    <TextBlock Grid.Row="1" Grid.Column="3">Topic:<Run Text="{Binding Topic}"></Run></TextBlock>
                </Grid>
            </Border>
        </DataTemplate>
        
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <DataGrid x:Name="LeftDG"
          Grid.Column="0"
          ItemsSource="{Binding Books}"
          VirtualizingPanel.IsVirtualizing="True"
          VirtualizingPanel.VirtualizationMode="Recycling"
          VirtualizingPanel.CacheLength="5,5"
          SnapsToDevicePixels="True"
          UseLayoutRounding="True"
          ScrollViewer.CanContentScroll="True"
          ScrollViewer.IsDeferredScrollingEnabled="False"
          AutoGenerateColumns="False"
          CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <Binding Source="{StaticResource DataGridDataTemplate}"/>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
            <behavior:Interaction.Behaviors>
                <local:SyncDatagridScrollBehavior TargetDG="{Binding ElementName=RightDG}"
                                                  BehaviorMainTitle="{Binding MainTitle,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
            </behavior:Interaction.Behaviors>
        </DataGrid>

        <DataGrid x:Name="RightDG"
              Grid.Column="1"
              ItemsSource="{Binding Books}"
              VirtualizingPanel.IsVirtualizing="True"
              VirtualizingPanel.VirtualizationMode="Recycling"
              VirtualizingPanel.CacheLength="5,5"
              SnapsToDevicePixels="True"
              UseLayoutRounding="True"
              ScrollViewer.CanContentScroll="True"
              ScrollViewer.IsDeferredScrollingEnabled="False"
              AutoGenerateColumns="False"
              CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <Binding Source="{StaticResource DataGridDataTemplate}"/>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
            <behavior:Interaction.Behaviors>
                <local:SyncDatagridScrollBehavior TargetDG="{Binding ElementName=LeftDG}"
                                                  BehaviorMainTitle="{Binding MainTitle,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
            </behavior:Interaction.Behaviors>
        </DataGrid>
    </Grid>
</Window>



using Microsoft.Xaml.Behaviors;
using System.Collections.ObjectModel;
using System.ComponentModel;
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;

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

    public class MainVM : INotifyPropertyChanged
    {
        private static long id = 1;
        private static (long, long) GetStartEnd(long interval)
        {
            long end = Interlocked.Add(ref id, interval);
            long start = end - interval;
            return (start, end);
        }

        public MainVM()
        {
            if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                return;
            }

            Books = new ObservableCollection<Book>();
            _ = InitBooksAsync();
        }

        private async Task InitBooksAsync(long cnt = 1000000)
        {
            var (start, end) = GetStartEnd(cnt);
            Books.Clear();

            await Task.Run(async () =>
            {
                List<Book> bks = new List<Book>();
                for (long i = start; i < end; i++)
                {
                    bks.Add(new Book()
                    {
                        Id = i,
                        Name = $"Name_{i}",
                        ISBN = $"ISBN_{i}_{Guid.NewGuid():N}",
                        Comment = $"Comment_{i}",
                        Content = $"Content_{i}",
                        Summary = $"Summary_{i}",
                        Title = $"Title_{i}",
                        Topic = $"Topic_{i}"
                    });
                }

                Application.Current?.Dispatcher.InvokeAsync(() =>
                {
                    Books = new ObservableCollection<Book>(bks);
                });
                await Task.Delay(0);
            });
        }

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

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

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

    public class SyncDatagridScrollBehavior : Behavior<DataGrid>
    {
        private ScrollViewer _sourceScrollViewer, _targetScrollViewer;
        private bool _isSyncScroll = false;
        public DataGrid TargetDG
        {
            get { return (DataGrid)GetValue(TargetDGProperty); }
            set { SetValue(TargetDGProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TargetDG.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TargetDGProperty =
            DependencyProperty.Register(nameof(TargetDG),
                typeof(DataGrid),
                typeof(SyncDatagridScrollBehavior),
                new PropertyMetadata(null, OnTargetDGChanged));

        private static void OnTargetDGChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var behavior = (SyncDatagridScrollBehavior)d;
            if (behavior != null)
            {
                behavior.RegisterEvents();
            }
        }



        public string BehaviorMainTitle
        {
            get { return (string)GetValue(BehaviorMainTitleProperty); }
            set { SetValue(BehaviorMainTitleProperty, value); }
        }

        // Using a DependencyProperty as the backing store for BehaviorMainTitle.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty BehaviorMainTitleProperty =
            DependencyProperty.Register(
                nameof(BehaviorMainTitle),
                typeof(string), 
                typeof(SyncDatagridScrollBehavior), 
                new PropertyMetadata(null));

        private void RegisterEvents()
        {
            if (TargetDG != null)
            {
                _targetScrollViewer = GetScrollViewer(TargetDG);
                if (_targetScrollViewer != null)
                {
                    _targetScrollViewer.ScrollChanged += _targetScrollViewer_ScrollChanged;
                }
            }
        }

        private void _targetScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            if (_isSyncScroll || _sourceScrollViewer == null)
            {
                return;
            }
            _isSyncScroll = true;
            try
            {
                _sourceScrollViewer.ScrollToVerticalOffset(e.VerticalOffset);
                _sourceScrollViewer.ScrollToHorizontalOffset(e.HorizontalOffset);
                BehaviorMainTitle = $"{DateTime.Now},VerticalOffset:{e.VerticalOffset},HorizontalOffset:{e.HorizontalOffset}";
            }
            finally
            {
                _isSyncScroll = false;
            }
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.Loaded += AssociatedObject_Loaded;
        }

        private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            _sourceScrollViewer = GetScrollViewer(AssociatedObject);
            if (_sourceScrollViewer != null)
            {
                _sourceScrollViewer.ScrollChanged += _sourceScrollViewer_ScrollChanged;
            }
        }

        private void _sourceScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            if (_isSyncScroll || _targetScrollViewer == null)
            {
                return;
            }

            _isSyncScroll = true;
            try
            {
                _targetScrollViewer.ScrollToVerticalOffset(e.VerticalOffset);
                _targetScrollViewer.ScrollToHorizontalOffset(e.HorizontalOffset);
                BehaviorMainTitle = $"{DateTime.Now},VerticalOffset:{e.VerticalOffset},HorizontalOffset:{e.HorizontalOffset}";
            }
            finally
            {
                _isSyncScroll = false;
            }
        }

        private ScrollViewer GetScrollViewer(DependencyObject dpObj)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dpObj); i++)
            {
                var child = VisualTreeHelper.GetChild(dpObj, i);
                if (child is ScrollViewer scrollViewer)
                {
                    return scrollViewer;
                }

                var result = GetScrollViewer(child);
                if (result != null)
                {
                    return result;
                }
            }
            return null;
        }
    }

    public class Book
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string ISBN { get; set; }
        public string Comment { get; set; }
        public string Content { get; set; }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
    }
}
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.Xaml.Behaviors;

public class SyncDataGridScrollBehavior : Behavior<DataGrid>
{
    private ScrollViewer _sourceScrollViewer;
    private ScrollViewer _targetScrollViewer;
    private bool _isSync = false;

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.Loaded += AssociatedObject_Loaded;
        AssociatedObject.Unloaded += AssociatedObject_Unloaded;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.Loaded -= AssociatedObject_Loaded;
        AssociatedObject.Unloaded -= AssociatedObject_Unloaded;
        UnsubscribeSource();
        UnsubscribeTarget();
    }

    #region TargetDataGrid Dependency Property

    public DataGrid TargetDataGrid
    {
        get => (DataGrid)GetValue(TargetDataGridProperty);
        set => SetValue(TargetDataGridProperty, value);
    }

    public static readonly DependencyProperty TargetDataGridProperty =
        DependencyProperty.Register(nameof(TargetDataGrid),
            typeof(DataGrid),
            typeof(SyncDataGridScrollBehavior),
            new PropertyMetadata(null, OnTargetDataGridChanged));

    private static void OnTargetDataGridChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behavior = (SyncDataGridScrollBehavior)d;
        behavior?.OnTargetDataGridChanged((DataGrid)e.OldValue, (DataGrid)e.NewValue);
    }

    private void OnTargetDataGridChanged(DataGrid oldValue, DataGrid newValue)
    {
        if (oldValue != null)
        {
            oldValue.Loaded -= TargetDataGrid_Loaded;
            UnsubscribeTarget();
        }

        if (newValue != null)
        {
            if (newValue.IsLoaded)
                SubscribeTargetScrollViewer(newValue);
            else
                newValue.Loaded += TargetDataGrid_Loaded;
        }
    }

    #endregion

    #region Event Handlers

    private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
    {
        SubscribeSourceScrollViewer(AssociatedObject);

        if (TargetDataGrid != null && TargetDataGrid.IsLoaded)
            SubscribeTargetScrollViewer(TargetDataGrid);
    }

    private void AssociatedObject_Unloaded(object sender, RoutedEventArgs e)
    {
        UnsubscribeSource();
        UnsubscribeTarget();
    }

    private void TargetDataGrid_Loaded(object sender, RoutedEventArgs e)
    {
        var target = sender as DataGrid;
        if (target == null) return;

        target.Loaded -= TargetDataGrid_Loaded;
        SubscribeTargetScrollViewer(target);
    }

    #endregion

    #region Subscribe / Unsubscribe Helpers

    private void SubscribeSourceScrollViewer(DataGrid dataGrid)
    {
        UnsubscribeSource();
        _sourceScrollViewer = FindScrollViewer(dataGrid);
        if (_sourceScrollViewer != null)
            _sourceScrollViewer.ScrollChanged += SourceScrollViewer_ScrollChanged;
    }

    private void SubscribeTargetScrollViewer(DataGrid dataGrid)
    {
        UnsubscribeTarget();
        _targetScrollViewer = FindScrollViewer(dataGrid);
        if (_targetScrollViewer != null)
            _targetScrollViewer.ScrollChanged += TargetScrollViewer_ScrollChanged;
    }

    private void UnsubscribeSource()
    {
        if (_sourceScrollViewer == null) return;
        _sourceScrollViewer.ScrollChanged -= SourceScrollViewer_ScrollChanged;
        _sourceScrollViewer = null;
    }

    private void UnsubscribeTarget()
    {
        if (_targetScrollViewer == null) return;
        _targetScrollViewer.ScrollChanged -= TargetScrollViewer_ScrollChanged;
        _targetScrollViewer = null;
    }

    #endregion

    #region Scroll Sync Core Logic

    private void SourceScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
    {
        if (_isSync || _targetScrollViewer == null)
            return;

        _isSync = true;
        try
        {
            _targetScrollViewer.ScrollToVerticalOffset(e.VerticalOffset);
            _targetScrollViewer.ScrollToHorizontalOffset(e.HorizontalOffset);
        }
        finally
        {
            _isSync = false;
        }
    }

    private void TargetScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
    {
        if (_isSync || _sourceScrollViewer == null)
            return;

        _isSync = true;
        try
        {
            _sourceScrollViewer.ScrollToVerticalOffset(e.VerticalOffset);
            _sourceScrollViewer.ScrollToHorizontalOffset(e.HorizontalOffset);
        }
        finally
        {
            _isSync = false;
        }
    }

    #endregion

    #region Visual Tree Search Helpers

    /// <summary>
    /// Recursively locate ScrollViewer inside visual tree
    /// </summary>
    private ScrollViewer FindScrollViewer(DependencyObject parent)
    {
        if (parent == null) return null;

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);

            if (child is ScrollViewer sv)
                return sv;

            var nestedResult = FindScrollViewer(child);
            if (nestedResult != null)
                return nestedResult;
        }
        return null;
    }

    /// <summary>
    /// Optimized lookup for DataGrid internal ScrollViewer
    /// </summary>
    private ScrollViewer FindDataGridScrollViewer(DataGrid dataGrid)
    {
        if (dataGrid == null) return null;

        var scrollViewer = FindScrollViewer(dataGrid);
        if (scrollViewer != null) return scrollViewer;

        dataGrid.ApplyTemplate();
        return FindScrollViewer(dataGrid);
    }

    #endregion
}