在ItemsControl

时间:2018-04-17 09:07:08

标签: wpf panel scrollviewer itemscontrol

我尝试使用IScrollInfo界面创建自定义面板,但收效甚微。如果我在XAML中手动声明自定义面板中的项目,我可以使它工作,但是当我将它放入ItemsControl时,滚动功能会停止。如果有人能告诉我哪里出错了,我真的很感激。这是面板的代码(相当冗长但很简单):

using IScrollInfoExample.Extentions;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace IScrollInfoExample
{
    public class ExampleScrollPanel : Panel, IScrollInfo
    {
        private TranslateTransform _trans = new TranslateTransform();
        private Size _extent = new Size(0, 0);
        private Size _viewport = new Size(0, 0);
        private Point _offset;
        private const double _scrollAmount = 3;

        public ExampleScrollPanel()
        {
            Loaded += ExampleScrollPanel_Loaded;
            RenderTransform = (_trans = new TranslateTransform());
        }

        public bool CanHorizontallyScroll { get; set; } = false;

        public bool CanVerticallyScroll { get; set; } = true;

        public double HorizontalOffset
        {
            get { return _offset.X; }
        }

        public double VerticalOffset
        {
            get { return _offset.Y; }
        }

        public double ExtentHeight
        {
            get { return _extent.Height; }
        }

        public double ExtentWidth
        {
            get { return _extent.Width; }
        }

        public double ViewportHeight
        {
            get { return _viewport.Height; }
        }

        public double ViewportWidth
        {
            get { return _viewport.Width; }
        }

        public ScrollViewer ScrollOwner { get; set; }

        public void LineUp()
        {
            SetVerticalOffset(VerticalOffset - _scrollAmount);
        }

        public void PageUp()
        {
            SetVerticalOffset(VerticalOffset - _viewport.Height);
        }

        public void MouseWheelUp()
        {
            SetVerticalOffset(VerticalOffset - _scrollAmount);
        }

        public void LineDown()
        {
            SetVerticalOffset(VerticalOffset + _scrollAmount);
        }

        public void PageDown()
        {
            SetVerticalOffset(VerticalOffset + _viewport.Height);
        }

        public void MouseWheelDown()
        {
            SetVerticalOffset(VerticalOffset + _scrollAmount);
        }

        public void LineLeft()
        {
            SetHorizontalOffset(HorizontalOffset - _scrollAmount);
        }

        public void PageLeft()
        {
            SetHorizontalOffset(HorizontalOffset - _viewport.Width);
        }

        public void MouseWheelLeft()
        {
            LineLeft();
        }

        public void LineRight()
        {
            SetHorizontalOffset(HorizontalOffset + _scrollAmount);
        }

        public void PageRight()
        {
            SetHorizontalOffset(HorizontalOffset + _viewport.Width);
        }

        public void MouseWheelRight()
        {
            LineRight();
        }

        public Rect MakeVisible(Visual visual, Rect rectangle)
        {
            return new Rect();
        }

        public void SetHorizontalOffset(double offset)
        {
            if (offset < 0 || _viewport.Width >= _extent.Width)
            {
                offset = 0;
            }
            else if (offset + _viewport.Width >= _extent.Width)
            {
                offset = _extent.Width - _viewport.Width;
            }
            _offset.X = offset;
            if (ScrollOwner != null) ScrollOwner.InvalidateScrollInfo();
            _trans.X = -offset;
        }

        public void SetVerticalOffset(double offset)
        {
            offset = CoerceVerticalOffset(offset);
            _offset.Y = offset;
            _trans.Y = -offset;
            if (ScrollOwner != null) ScrollOwner.InvalidateScrollInfo();
        }

        private double CoerceVerticalOffset(double offset)
        {
            if (offset < 0 || _viewport.Height >= _extent.Height)
            {
                offset = 0;
            }
            else if (offset + _viewport.Height >= _extent.Height)
            {
                offset = _extent.Height - _viewport.Height;
            }
            return offset;
        }

        private void ExampleScrollPanel_Loaded(object sender, RoutedEventArgs e)
        {
            ScrollViewer scrollOwner = this.GetParentOfType<ScrollViewer>();
            if (scrollOwner != null) ScrollOwner = scrollOwner;
        }

        protected override Size MeasureOverride(Size availableSize)
        {
            UpdateScrollInfo(availableSize);
            Size totalSize = new Size();
            foreach (UIElement child in InternalChildren)
            {
                child.Measure(availableSize);
                totalSize.Height += child.DesiredSize.Height;
                totalSize.Width = Math.Max(totalSize.Width, child.DesiredSize.Width);
            }
            return base.MeasureOverride(totalSize);
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            UpdateScrollInfo(finalSize);
            double verticalPosition = 0;

            int childCount = InternalChildren.Count;
            for (int i = 0; i < childCount; i++)
            {
                UIElement child = InternalChildren[i];
                child.Arrange(new Rect(0, verticalPosition, finalSize.Width, finalSize.Height));
                verticalPosition += child.DesiredSize.Height;
            }
            return base.ArrangeOverride(finalSize);
        }

        private void UpdateScrollInfo(Size availableSize)
        {
            bool viewportChanged = false, extentChanged = false;
            Size extent = CalculateExtent(availableSize);
            if (extent != _extent)
            {
                _extent = extent;
                extentChanged = true;
            }
            if (availableSize != _viewport)
            {
                _viewport = availableSize;
                viewportChanged = true;
            }
            if (extentChanged || viewportChanged) ScrollOwner?.InvalidateScrollInfo();
        }

        private Size CalculateExtent(Size availableSize)
        {
            Size totalExtentSize = new Size();
            foreach (UIElement child in InternalChildren)
            {
                child.Measure(availableSize);
                totalExtentSize.Height += child.DesiredSize.Height;
                totalExtentSize.Width = Math.Max(totalExtentSize.Width, child.DesiredSize.Width);
            }
            return totalExtentSize;
        }
    }
}

现在MainWindow.xaml.cs

<Window x:Class="IScrollInfoExample.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:IScrollInfoExample"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
    <ScrollViewer CanContentScroll="True">
        <ItemsControl ItemsSource="{Binding Buttons, RelativeSource={RelativeSource AncestorType={x:Type Local:MainWindow}}}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Local:ExampleScrollPanel IsItemsHost="True" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Height="100" Width="250" HorizontalAlignment="Center" Content="{Binding}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
        <!--<Local:ExampleScrollPanel>
            <Button Height="100" Width="250" HorizontalAlignment="Center" Content="A" />
            <Button Height="100" Width="250" HorizontalAlignment="Center" Content="B" />
            <Button Height="100" Width="250" HorizontalAlignment="Center" Content="C" />
            <Button Height="100" Width="250" HorizontalAlignment="Center" Content="D" />
            <Button Height="100" Width="250" HorizontalAlignment="Center" Content="E" />
            <Button Height="100" Width="250" HorizontalAlignment="Center" Content="F" />
            <Button Height="100" Width="250" HorizontalAlignment="Center" Content="G" />
            <Button Height="100" Width="250" HorizontalAlignment="Center" Content="H" />
            <Button Height="100" Width="250" HorizontalAlignment="Center" Content="I" />
        </Local:ExampleScrollPanel>-->
    </ScrollViewer>
</Window>

背后的代码:

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;

namespace IScrollInfoExample
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Buttons = new ObservableCollection<string>();
            IEnumerable<int> characterCodes = Enumerable.Range(65, 26);
            foreach (int characterCode in characterCodes) Buttons.Add(((char)characterCode).ToString().ToUpper());
        }

        public static readonly DependencyProperty ButtonsProperty = DependencyProperty.Register(nameof(Buttons), typeof(ObservableCollection<string>), typeof(MainWindow), null);

        public ObservableCollection<string> Buttons
        {
            get { return (ObservableCollection<string>)GetValue(ButtonsProperty); }
            set { SetValue(ButtonsProperty, value); }
        }
    }
}

首先查看XAML,您可以看到手动添加的Button对象。运行应用程序,您应该在面板中看到一些可垂直滚动的按钮...到目前为止,非常好。如果您在MouseWheelUpMouseWheelDown方法中添加断点并滚动,则会注意到断点会立即被点击。

现在,如果您使用手动创建的按钮注释掉较低的ExampleScrollPanel并取消注释上面的ItemsControl,则您会看到滚动项目的功能已消失。我的问题是&#34; 当自定义面板托管在ItemsControl元素中时,如何使滚动工作?&#34;

请注意,ScrollOwner属性是使用自定义GetParentOfType<T>方法填充的,该方法会成功找到相应的ScrollViewer,并且不是导致此问题的原因。因此,我没有为此方法添加基于VisualTreeHelper的代码。

此外,我注意到,当面板位于ItemsControl内时,滚动条不再显示,但我检查了该面板的extentviewport值似乎仍然是获得更新成功。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

ItemsControl没有自己的ScrollViewer,并且无法访问您为此目的提供的外部版本。您需要使用ScrollViewer属性添加ItemsControl ItemsControl.Template可以访问的<ItemsControl ItemsSource="{Binding Buttons, RelativeSource={RelativeSource AncestorType={x:Type Local:MainWindow}}}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Local:ExampleScrollPanel /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.Template> <ControlTemplate TargetType="{x:Type ItemsControl}"> <!--Add the ScrollViewer here, inside the ControlTemplate--> <ScrollViewer CanContentScroll="True"> <!--Your items will be added here--> <ItemsPresenter/> </ScrollViewer> </ControlTemplate> </ItemsControl.Template> <ItemsControl.ItemTemplate> <DataTemplate> <Button Height="100" Width="250" HorizontalAlignment="Center" Content="{Binding}" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> ,如下所示:

ScrollViewer

请注意,您必须将True的{​​{3}}设置为IScrollInfo,以告知您已在面板中实施了start_matlab界面,并希望接管滚动功能。