WPF 平移ListBox翻页

  因为需要做个类似的东西,在版面的移动以及布局上需要学习的东西还是很多的。普通的Panel已经不能满足我的需求了,所以需要重新来自定义一个Panel来放入ListBox中,我做了一个DEMO,首先弄一个ListBox,把他的Template、ItemSource、Detetemplate等东西都先设置一下,这个我以前都写过学习过了,然后建一个类,这个类我们用来滑动以及设计模板,首先设置它的MeasureOverride和ArrangeOverride,这两个方法是WPF的Layout系统提供给用户的自定义接口,一个是测量范围给出所需要的范围,一个是安排Child的位置。这个玩意还是比较搞的,可以参考一下:

http://www.cnblogs.com/powertoolsteam/archive/2011/01/10/1932036.htmlhttp://www.cnblogs.com/powertoolsteam/archive/2011/01/11/1932923.html

来先大致了解一下这两个方法。其中还是有许多可以研究的东西的。

  我设置了ListBoxItem的大小为一个200的正方形,随便弄了18个Item,我把这些Item分成2排根据窗口的大小来自动设置应该放几个Item在窗口中,然后多余的空白平均分布在两侧。Measure和Arrange的方法如下所示:

View Code
protected override Size MeasureOverride(Size constraint) {
            double dWidth = Math.Floor(constraint.Width / 200.00);
            double dHeight = Math.Floor(constraint.Height / 200.00);
            Size s = new Size(Math.Ceiling(InternalChildren.Count / (dWidth * dHeight)) * constraint.Width, constraint.Height);

            Size extentTmp = new Size(s.Width * this.InternalChildren.Count, constraint.Height);
            foreach (UIElement each in InternalChildren) {
                each.Measure(new Size(200, 200));
            }
            if (extentTmp != extent) {
                extent = s;
            }
            if (viewport != constraint) {
                viewport = constraint;
            }
            return s;
        }
View Code
protected override Size ArrangeOverride(Size arrangeSize) {
            int count = (int)Math.Floor(viewport.Width / 200.00);
            page = (int)Math.Ceiling((decimal)InternalChildren.Count / (count * 2));
            int temp = 0;
            int n = 2;
            int countView = 0;
            try {
                for (int i = 0; i < InternalChildren.Count; i++) {
                    this.InternalChildren[i].Arrange(new Rect((200 * (i - countView * 2 * count)) + (viewport.Width * countView) + ((viewport.Width - count * 200) / 2), 50, 200, 200));
                    temp++;
                    if (temp > count) {
                        for (int j = i; j < n * count; j++) {
                            this.InternalChildren[j].Arrange(new Rect(200 * (j - count - countView * 2 * count) + (viewport.Width * countView) + ((viewport.Width - count * 200) / 2), 250, 200, 200));
                            i = j;
                        }
                        countView++;
                        n += 2;
                        temp = 0;
                    }
                }
            } catch (ArgumentOutOfRangeException) { }
            return arrangeSize;
        }

  这样就布局出了一个根据Item大小及多少所来弄出适当的Panel,同时在拉框体的时候还能够自适应Panel,这样比原来的Panel更加的灵活。

  接下来就是要拖拉的效果。同样在这个类中,首先当鼠标按下的时候,先要CaptureMouse,这样就不会因为拉出窗口而失去鼠标的坐标,因为我只是左右拉,所以只需要获取到的X坐标。然后在MouseUp的时候再获取X的坐标然后判断,只要超出一定范围就能够判断是否拖拉,这样再执行一个的动画,因为设置了Measure,然后移动你的窗口的大小的范围就能够做到拖拉效果。其中知道自己有多少页就能够判断在第零页以及最后一页不能拖拉。

下面给出我做的小DEMO:https://files.cnblogs.com/socialdk/SliderTest.zip

原文地址:https://www.cnblogs.com/socialdk/p/2717312.html