c# - 在 WinRT/UWP 中创建自定义虚拟化控件

标签 c# windows-store-apps winrt-xaml uwp

在 WPF 中,FrameworkElement 派生类可以通过 AddVisualChild 提供自己的子类。这样就可以实现您自己的虚拟化控件,这些控件只生成可见的子项。您也可以在没有后备集合的情况下生成 child 。

我想使用此技术将几个控件从 WPF 移植到 Windows 10 UWP,但不清楚如何在 WinRT UI 中正确实现虚拟化。因为在对问题的原始版本的评论中指出,询问实现技术对于 Stack Overflow 来说过于笼统,所以我创建了一个简约示例来解释我试图涵盖的关键功能,这些功能是

  • 从数据模型动态生成子控件
  • 为生成的子控件执行自定义布局逻辑

我做了以下考虑:

  • 据我所知,自定义控件不可能像在 WPF 中那样管理自己的子控件
  • 我排除了 Panel 子类,因为当我的自定义控件(由其他人)使用时,很容易出错。面板子项应该由包含的 XAML 而不是面板控制。
  • 我排除了 ItemsControl 子类,因为它不太可能提供后备集合(数据虚拟化是一项要求)

(请注意,将它们排除在外可能是错误的,所以如果是,请指出。)

以下 WPF 代码创建了一个无限滚动的日期带,但只具体化了当前可见的单元格。我有意使其尽可能简约,因此它没有多大意义,但它确实提供了我上面提到的两个关键功能,我需要了解如何在 WinRT 中实现它们。

所以我的问题是:是否可以在 WinRT 中创建这样一个动态构建其子项以显示无限滚动带的控件?请记住,它需要是独立的,以便放置在任意页面上而页面不必包含额外的代码(否则它根本就不是可重用的控件)。

如果您已经知道如何实现虚拟化并且可以给我一些提示,我认为足以回答概述如何在 WinRT 中完成它。

WPF 来源:

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace Sandbox
{
    public class DateBand : FrameworkElement
    {
        public static readonly DependencyProperty ScrollOffsetProperty = DependencyProperty.Register(
            nameof(ScrollOffset), typeof(double), typeof(DateBand), new FrameworkPropertyMetadata {
                AffectsMeasure = true,
            });

        public double ScrollOffset
        {
            get { return (double)GetValue(ScrollOffsetProperty); }
            set { SetValue(ScrollOffsetProperty, value); }
        }

        public static readonly DependencyProperty CellTemplateProperty = DependencyProperty.Register(
            nameof(CellTemplate), typeof(DataTemplate), typeof(DateBand), new FrameworkPropertyMetadata {
                AffectsMeasure = true,
            });

        public DataTemplate CellTemplate
        {
            get { return (DataTemplate)GetValue(CellTemplateProperty); }
            set { SetValue(CellTemplateProperty, value); }
        }

        private List<DateCell> _cells = new List<DateCell>();
        private DateTime _startDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
        private const double cSlotWidth = 5;
        private const double cSlotHeight = 20;

        protected override int VisualChildrenCount => _cells.Count;
        protected override Visual GetVisualChild(int index) => _cells[index];

        protected override Size MeasureOverride(Size availableSize)
        {
            int usedCells = 0;
            double desiredWidth = 0;
            double desiredHeight = 0;

            if (!double.IsPositiveInfinity(availableSize.Height))
            {
                var index = (int)Math.Floor(ScrollOffset);
                var offset = (index - ScrollOffset) * cSlotHeight;

                while (offset < availableSize.Height)
                {
                    DateCell cell;
                    if (usedCells < _cells.Count)
                    {
                        cell = _cells[usedCells];
                    }
                    else
                    {
                        cell = new DateCell();
                        AddVisualChild(cell);
                        _cells.Add(cell);
                    }
                    usedCells++;

                    var cellValue = _startDate.AddMonths(index);
                    cell._offset = offset;
                    cell._width = DateTime.DaysInMonth(cellValue.Year, cellValue.Month) * cSlotWidth;
                    cell.Content = cellValue;
                    cell.ContentTemplate = CellTemplate;
                    cell.Measure(new Size(cell._width, cSlotHeight));

                    offset += cSlotHeight;
                    index++;

                    desiredHeight = Math.Max(desiredHeight, offset);
                    desiredWidth = Math.Max(desiredWidth, cell._width);
                }
            }

            if (usedCells < _cells.Count)
            {
                for (int i = usedCells; i < _cells.Count; i++)
                    RemoveVisualChild(_cells[i]);

                _cells.RemoveRange(usedCells, _cells.Count - usedCells);
            }

            return new Size(desiredWidth, desiredHeight);
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            foreach (var cell in _cells)
                cell.Arrange(new Rect(0, cell._offset, cell._width, cell.DesiredSize.Height));

            return finalSize;
        }
    }

    public class DateCell : ContentControl
    {
        internal double _offset;
        internal double _width;
    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            Band.SetCurrentValue(DateBand.ScrollOffsetProperty, Band.ScrollOffset - e.Delta / Mouse.MouseWheelDeltaForOneLine);
        }
    }
}

WPF XAML:

<Window x:Class="Sandbox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Sandbox"
        MouseWheel="Window_MouseWheel">
    <DockPanel>
        <ScrollBar x:Name="Scroll" Orientation="Vertical" Minimum="-24" Maximum="+24" ViewportSize="6"/>
        <local:DateBand x:Name="Band" ScrollOffset="{Binding ElementName=Scroll, Path=Value, Mode=OneWay}">
            <local:DateBand.CellTemplate>
                <DataTemplate>
                    <Border BorderBrush="Black" BorderThickness="1" Padding="5,2">
                        <TextBlock Text="{Binding StringFormat='yyyy - MMMM'}"/>
                    </Border>
                </DataTemplate>
            </local:DateBand.CellTemplate>
        </local:DateBand>
    </DockPanel>
</Window>

最佳答案

根据评论中的要求,我发布了我最终得到的解决方案。我只想出了使用某种 Panel 子类的解决方案,所以我想出了将控件分成两部分的折衷方案,以避免控件的用户意外弄乱子集合。

所以我实际上有两个主要类,一个 Control 子类公开公共(public) API(如依赖属性)并支持主题,一个 Panel 子类实现实际的虚拟化。两者都通过 XAML 模板链接,如果有人在预期控制之外使用它,Panel 子类将拒绝执行任何工作。

完成后,虚拟化就非常简单了,与您在 WPF 中的做法没有太大区别 - 只需修改面板的子项,例如在 MeasureOverride 中。

为了说明,我已将代码从问题移植到 UWP,如下所示:

UWP 来源:

[TemplatePart(Name = PanelPartName, Type = typeof(DateBandPanel))]
public class DateBand : Control
{
    private const string PanelPartName = "CellPanel";

    public static readonly DependencyProperty ScrollOffsetProperty = DependencyProperty.Register(
        nameof(ScrollOffset), typeof(double), typeof(DateBand), new PropertyMetadata(
            (double)0, new PropertyChangedCallback((d, e) => ((DateBand)d).HandleScrollOffsetChanged(e))));

    private void HandleScrollOffsetChanged(DependencyPropertyChangedEventArgs e)
    {
        _panel?.InvalidateMeasure();
    }

    public double ScrollOffset
    {
        get { return (double)GetValue(ScrollOffsetProperty); }
        set { SetValue(ScrollOffsetProperty, value); }
    }

    public static readonly DependencyProperty CellTemplateProperty = DependencyProperty.Register(
        nameof(CellTemplate), typeof(DataTemplate), typeof(DateBand), new PropertyMetadata(
            null, new PropertyChangedCallback((d, e) => ((DateBand)d).HandleCellTemplateChanged(e))));

    private void HandleCellTemplateChanged(DependencyPropertyChangedEventArgs e)
    {
        _panel?.InvalidateMeasure();
    }

    public DataTemplate CellTemplate
    {
        get { return (DataTemplate)GetValue(CellTemplateProperty); }
        set { SetValue(CellTemplateProperty, value); }
    }

    private DateBandPanel _panel;

    public DateBand()
    {
        this.DefaultStyleKey = typeof(DateBand);
    }

    protected override void OnApplyTemplate()
    {
        if (_panel != null)
            _panel._band = null;

        base.OnApplyTemplate();

        _panel = GetTemplateChild(PanelPartName) as DateBandPanel;

        if (_panel != null)
            _panel._band = this;
    }
}

public class DateBandPanel : Panel
{
    internal DateBand _band;
    private List<DateCell> _cells = new List<DateCell>();
    private DateTime _startDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
    private const double cSlotWidth = 5;
    private const double cSlotHeight = 26;

    protected override Size MeasureOverride(Size availableSize)
    {
        int usedCells = 0;
        double desiredWidth = 0;
        double desiredHeight = 0;

        if (!double.IsPositiveInfinity(availableSize.Height) && _band != null)
        {
            var index = (int)Math.Floor(_band.ScrollOffset);
            var offset = (index - _band.ScrollOffset) * cSlotHeight;

            while (offset < availableSize.Height)
            {
                DateCell cell;
                if (usedCells < _cells.Count)
                {
                    cell = _cells[usedCells];
                }
                else
                {
                    cell = new DateCell();
                    Children.Add(cell);
                    _cells.Add(cell);
                }
                usedCells++;

                var cellValue = _startDate.AddMonths(index);
                cell._offset = offset;
                cell._width = DateTime.DaysInMonth(cellValue.Year, cellValue.Month) * cSlotWidth;
                cell.Content = new CellData(cellValue);
                cell.ContentTemplate = _band.CellTemplate;
                cell.Measure(new Size(cell._width, cSlotHeight));

                offset += cSlotHeight;
                index++;

                desiredHeight = Math.Max(desiredHeight, offset);
                desiredWidth = Math.Max(desiredWidth, cell._width);
            }
        }

        if (usedCells < _cells.Count)
        {
            for (int i = usedCells; i < _cells.Count; i++)
                Children.Remove(_cells[i]);

            _cells.RemoveRange(usedCells, _cells.Count - usedCells);
        }

        return new Size(desiredWidth, desiredHeight);
    }

    protected override Size ArrangeOverride(Size finalSize)
    {
        foreach (var cell in _cells)
            cell.Arrange(new Rect(0, cell._offset, cell._width, cell.DesiredSize.Height));

        return finalSize;
    }
}

public class CellData
{
    public DateTime Date { get; }
    public CellData(DateTime date) { this.Date = date; }
}

public class DateCell : ContentControl
{
    internal double _offset;
    internal double _width;
}

public class FormattingConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null)
            return null;

        if (parameter == null)
            return value.ToString();

        return ((IFormattable)value).ToString((string)parameter, CultureInfo.CurrentCulture);
    }

    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotSupportedException();
    }
}

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    private void Page_PointerWheelChanged(object sender, PointerRoutedEventArgs e)
    {
        Scroll.Value -= e.GetCurrentPoint(this).Properties.MouseWheelDelta / 120.0;
    }
}

UWP XAML 页面:

<Page x:Class="Sandbox.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:Sandbox"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      mc:Ignorable="d"
      PointerWheelChanged="Page_PointerWheelChanged">
    <Page.Resources>
        <local:FormattingConverter x:Key="FormattingConverter"/>
    </Page.Resources>
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <ScrollBar x:Name="Scroll" Grid.Column="0" Orientation="Vertical" IndicatorMode="MouseIndicator" Minimum="-24" Maximum="+24" ViewportSize="6"/>
        <local:DateBand x:Name="Band" Grid.Column="1" ScrollOffset="{Binding ElementName=Scroll, Path=Value, Mode=OneWay}">
            <local:DateBand.CellTemplate>
                <DataTemplate x:DataType="local:CellData">
                    <Border BorderBrush="Black" BorderThickness="1" Padding="5,2">
                        <TextBlock Text="{x:Bind Path=Date, Converter={StaticResource FormattingConverter}, ConverterParameter='yyyy - MMMM'}"/>
                    </Border>
                </DataTemplate>
            </local:DateBand.CellTemplate>
        </local:DateBand>
    </Grid>
</Page>

UWP XAML 主题:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:local="using:Sandbox">
    <Style TargetType="local:DateBand" >
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:DateBand">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <local:DateBandPanel Name="CellPanel"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

关于c# - 在 WinRT/UWP 中创建自定义虚拟化控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33961153/

相关文章:

javascript - Windows 8 Store 应用程序,如何测试应用程序内购买?

c# - 无法删除 Windows 应用商店应用程序中的文件 - 访问被拒绝。 (HRESULT : 0x80070005 (E_ACCESSDENIED))

windows-runtime - 仅使用 StreamReader/StreamWriter 在 WinRT 中读取/写入大型文本文件?

xaml - 通用Windows应用程序: programmatically change font sizes application wide

c# - 自定义 View 层次结构的语义缩放,而不是普通的网格或 ListView

c# - XML架构

c# - 2 个 ObservableCollections 1 个组合框 WPF

data-binding - “UpdateSourceTrigger=PropertyChanged” 等效于 WinRT-XAML 中的文本框

javascript - 我无法通过 Jquery 弹出窗口更新数据

c# - 自动迁移如何在 Entity Framework 4.3 内部工作