还有的时候,会遇到DataGrid里面嵌套DataGrid(重叠嵌套),然后里面的鼠标滚轮无法响应外面的滚动,为此记录下解决方案

与上一篇区别在于,详情里面的模板通常是通用的,被定义在样式文件中,被重复使用,因此无法为其添加后台代码,如果能添加后台代码,请查看第一篇;所以需要用到命令的方式来辅助事件的抛出,当然还可以利用第三方库Prism,他可以把事件当命令传递,且能传递事件的默认参数,详情请参阅这篇文章;好了,下面开始介绍,扩展DataGrid类,通过自定义命令抛出事件,并传递事件参数...

先请大致看下运行效果:

下面是详情代码,尾部有完整demo,下载

 

<Window x:Class="CustomCommand.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:local="clr-namespace:CustomCommand"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="MainWindow" Height="400" Width="300">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <DataGrid x:Name="datagrid" RowDetailsTemplate="{StaticResource RowDetails}"/>
    </Grid>
</Window>
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:CustomCommand">

    <Style TargetType="DataGrid">
        <Setter Property="IsReadOnly" Value="True" />
        <Setter Property="CanUserAddRows" Value="False" />
        <Setter Property="CanUserDeleteRows" Value="False" />
        <Setter Property="VirtualizingPanel.ScrollUnit" Value="Pixel" />
    </Style>
    
    <!--为了不影响已设置的最基础样式,所以下面这个集成样式很重要-->
    <Style TargetType="local:CustomDataGrid" BasedOn="{StaticResource {x:Type DataGrid}}" />

    <DataTemplate x:Key="RowDetails">
        <local:CustomDataGrid ItemsSource="{Binding Infos}" 
                              MouseWheelCommand="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window},Path=MouseWheelCommand}" />
    </DataTemplate>
</ResourceDictionary>

特别注明下:为了不影响整体样式,需要继承基础样式,否则应用到项目会有区别的

 <!--为了不影响已设置的最基础样式,所以下面这个集成样式很重要-->
 <Style TargetType="local:CustomDataGrid" BasedOn="{StaticResource {x:Type DataGrid}}" />

 

using Prism.Commands;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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;

namespace CustomCommand
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 鼠标滚动时发送
        /// </summary>
        public ICommand MouseWheelCommand { get; private set; }

        public ObservableCollection<Info> Datas = new ObservableCollection<Info>();

        public MainWindow()
        {
            MouseWheelCommand = new DelegateCommand<object>(CustomMouseWheel);

            InitializeComponent();
            datagrid.ItemsSource = Datas;

            for (int i = 0; i < 50; i++)
            {
                var info = new Info();
                info.name = "第一级" + i;
                Datas.Add(info);

                if (i % 2 == 0)
                {
                    for (int j = 0; j < 20; j++)
                    {
                        info.Infos.Add(new Info()
                        {
                            name = "第二级" + j
                        });
                    }
                }
            }
        }


        /// <summary>
        /// 当DataGrid的详情行里的DataGrid滚动时发生
        /// </summary>
        /// <param name="obj"></param>
        void CustomMouseWheel(object p)
        {
            if (p is MouseWheelEventArgs e)
            {
                var sc = GetVisualChild<ScrollViewer>(datagrid);
                if (sc != null)
                {
                    sc.ScrollToVerticalOffset(sc.VerticalOffset - e.Delta);
                }
            }
        }

        T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T child = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                var v = (Visual)VisualTreeHelper.GetChild(parent, i);
                child = v as T ?? GetVisualChild<T>(v);
                if (child != null)
                    break;
            }
            return child;
        }
    }

    public class Info
    {
        public string name { get; set; }

        public ObservableCollection<Info> Infos { get; set; } = new ObservableCollection<Info>();
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace CustomCommand
{
    /// <summary>
    /// 自定义扩展DataGrid  主要是用于响应滚轮事件
    /// </summary>
    public class CustomDataGrid : DataGrid
    {
        public CustomDataGrid()
        {
            PreviewMouseWheel += CustomDataGrid_PreviewMouseWheel;
        }

        /// <summary>
        /// 鼠标滚动滚动时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CustomDataGrid_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            MouseWheelCommand?.Execute(e);//触发命令,并把MouseWheelEventArgs传递
        }

        /// <summary>
        /// 声明一个用于滚动通知的命令
        /// </summary>
        public ICommand MouseWheelCommand
        {
            get { return (ICommand)GetValue(MouseWheelCommandProperty); }
            set { SetValue(MouseWheelCommandProperty, value); }
        }

        public static readonly DependencyProperty MouseWheelCommandProperty =
            DependencyProperty.Register("MouseWheelCommand", typeof(ICommand), typeof(CustomDataGrid), new PropertyMetadata(default(ICommand)));

    }
}

下面是完整demo,有需要的可以下载

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
DataGrid滚轮问题是指在嵌套DataGrid中,里面鼠标滚轮无法响应外部的滚动解决这个问题的方法可以采用自定义命令传递滚轮事件参数的方式来实现。具体原理是采用像素滚动方式,通过捕获里面DataGrid鼠标滚轮事件,然后获取到外部DataGrid的ScrollViewer对象,将滚动的量设置给ScrollViewer即可。通过这种方式,可以实现内外DataGrid滚轮联动效果。详情请参考https://blog.csdn.net/u010438205/article/details/105710794。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [有的时候,遇到DataGrid里面嵌套DataGrid重叠嵌套),然后里面鼠标滚轮无法响应外面滚动,为此记录...](https://blog.csdn.net/u010438205/article/details/105659330)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [2.0DataGrid嵌套DataGrid里面鼠标滚动响应到外部,利用自定义命令传递滚轮事件参数实现](https://download.csdn.net/download/u010438205/12355290)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值