■ ItemsRepeater 엘리먼트의 Layout 속성에서 VirtualizingLayout 상속 객체를 만들어 가상화/스크롤 가능한 커스텀 레이아웃을 사용하는 방법을 보여준다.
▶ ActivityFeedLayoutState.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
using System.Collections.Generic; using Windows.Foundation; namespace TestProject { /// <summary> /// 활동 피드 레이아웃 상태 /// </summary> public class ActivityFeedLayoutState { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 레이아웃 사각형 리스트 /// </summary> private List<Rect> layoutRectList; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Publoc #region 첫번째 실현 인덱스 - FirstRealizedIndex /// <summary> /// 첫번째 실현 인덱스 /// </summary> public int FirstRealizedIndex { get; set; } #endregion #region 레이아웃 사각형 리스트 - LayoutRectList /// <summary> /// 레이아웃 사각형 리스트 /// </summary> public List<Rect> LayoutRectList { get { if(this.layoutRectList == null) { this.layoutRectList = new List<Rect>(); } return this.layoutRectList; } } #endregion } } |
▶ ActivityFeedLayout.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 |
using System; using Windows.Foundation; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml; namespace TestProject { /// <summary> /// 활동 피드 레이아웃 /// </summary> public class ActivityFeedLayout : VirtualizingLayout { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 행 간격 속성 - RowSpacingProperty /// <summary> /// 행 간격 속성 /// </summary> public static readonly DependencyProperty RowSpacingProperty = DependencyProperty.Register ( "RowSpacing", typeof(double), typeof(ActivityFeedLayout), new PropertyMetadata(0, PropertyChangedCallback) ); #endregion #region 열 간격 속성 - ColumnSpacingProperty /// <summary> /// 열 간격 속성 /// </summary> public static readonly DependencyProperty ColumnSpacingProperty = DependencyProperty.Register ( "ColumnSpacing", typeof(double), typeof(ActivityFeedLayout), new PropertyMetadata(0, PropertyChangedCallback) ); #endregion #region 최소 항목 크기 속성 - MinimumItemSizeProperty /// <summary> /// 최소 항목 크기 속성 /// </summary> public static readonly DependencyProperty MinimumItemSizeProperty = DependencyProperty.Register ( "MinimumItemSize", typeof(Size), typeof(ActivityFeedLayout), new PropertyMetadata(Size.Empty, PropertyChangedCallback) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 행 간격 /// </summary> private double rowSpacing; /// <summary> /// 열 간격 /// </summary> private double columnSpacing; /// <summary> /// 최소 항목 크기 /// </summary> private Size minimumItemSize = Size.Empty; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 행 간격 - RowSpacing /// <summary> /// 행 간격 /// </summary> public double RowSpacing { get { return this.rowSpacing; } set { SetValue(RowSpacingProperty, value); } } #endregion #region 열 간격 - ColumnSpacing /// <summary> /// 열 간격 /// </summary> public double ColumnSpacing { get { return this.columnSpacing; } set { SetValue(ColumnSpacingProperty, value); } } #endregion #region 최소 항목 크기 - MinimumItemSize /// <summary> /// 최소 항목 크기 /// </summary> public Size MinimumItemSize { get { return this.minimumItemSize; } set { SetValue(MinimumItemSizeProperty, value); } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 속성 변경시 콜백 처리하기 - PropertyChangedCallback(d, e) /// <summary> /// 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">의존 객체</param> /// <param name="e">이벤트 인자</param> private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ActivityFeedLayout layout = d as ActivityFeedLayout; if(e.Property == RowSpacingProperty) { layout.rowSpacing = (double)e.NewValue; } else if(e.Property == ColumnSpacingProperty) { layout.columnSpacing = (double)e.NewValue; } else if(e.Property == MinimumItemSizeProperty) { layout.minimumItemSize = (Size)e.NewValue; } else { throw new InvalidOperationException("Don't know what you are talking about!"); } layout.InvalidateMeasure(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Protected #region 컨텍스트용 초기화하기 (코어) - InitializeForContextCore(context) /// <summary> /// 컨텍스트용 초기화하기 (코어) /// </summary> /// <param name="context">가상화 레이아웃 컨텍스트</param> protected override void InitializeForContextCore(VirtualizingLayoutContext context) { base.InitializeForContextCore(context); if(!(context.LayoutState is ActivityFeedLayoutState)) { context.LayoutState = new ActivityFeedLayoutState(); } } #endregion #region 컨텍스트용 초기화 취소하기 (코어) - UninitializeForContextCore(context) /// <summary> /// 컨텍스트용 초기화 취소하기 (코어) /// </summary> /// <param name="context">가상화 레이아웃 컨텍스트</param> protected override void UninitializeForContextCore(VirtualizingLayoutContext context) { base.UninitializeForContextCore(context); context.LayoutState = null; } #endregion #region 측정하기 (오버라이드) - MeasureOverride(context, availableSize) /// <summary> /// 측정하기 (오버라이드) /// </summary> /// <param name="context">가상화 레이아웃 컨텍스트</param> /// <param name="availableSize">이용 가능한 크기</param> /// <returns>측정 크기</returns> protected override Size MeasureOverride(VirtualizingLayoutContext context, Size availableSize) { if(MinimumItemSize == Size.Empty) { UIElement firstElement = context.GetOrCreateElementAt(0); firstElement.Measure(new Size(float.PositiveInfinity, float.PositiveInfinity)); this.minimumItemSize = firstElement.DesiredSize; } int firstRowIndex = Math.Max ( (int)(context.RealizationRect.Y / (MinimumItemSize.Height + RowSpacing)) - 1, 0 ); int lastRowIndex = Math.Min ( (int)(context.RealizationRect.Bottom / (this.MinimumItemSize.Height + this.RowSpacing)) + 1, (int)(context.ItemCount / 3) ); ActivityFeedLayoutState state = context.LayoutState as ActivityFeedLayoutState; state.LayoutRectList.Clear(); state.FirstRealizedIndex = firstRowIndex * 3; double desiredItemWidth = Math.Max ( this.MinimumItemSize.Width, (availableSize.Width - ColumnSpacing * 3) / 4 ); for(int rowIndex = firstRowIndex; rowIndex < lastRowIndex; rowIndex++) { int firstItemIndex = rowIndex * 3; Rect[] boundRectangleArrayForCurrentRow = CalculateLayoutBoundRectangleArrayForRow(rowIndex, desiredItemWidth); for(int columnIndex = 0; columnIndex < 3; columnIndex++) { int index = firstItemIndex + columnIndex; UIElement containerElement = context.GetOrCreateElementAt(index); containerElement.Measure ( new Size ( boundRectangleArrayForCurrentRow[columnIndex].Width, boundRectangleArrayForCurrentRow[columnIndex].Height ) ); state.LayoutRectList.Add(boundRectangleArrayForCurrentRow[columnIndex]); } } double extentHeight; if(context.ItemCount == 0) { extentHeight = 0; } else { extentHeight = ((int)(context.ItemCount / 3) - 1) * (MinimumItemSize.Height + RowSpacing) + MinimumItemSize.Height; } return new Size(desiredItemWidth * 4 + this.ColumnSpacing * 2, extentHeight); } #endregion #region 배치하기 (오버라이드) - ArrangeOverride(context, finalSize) /// <summary> /// 배치하기 (오버라이드) /// </summary> /// <param name="context">가상화 레이아웃 컨텍스트</param> /// <param name="finalSize">최종 크기</param> /// <returns>배치 크기</returns> protected override Size ArrangeOverride(VirtualizingLayoutContext context, Size finalSize) { ActivityFeedLayoutState state = context.LayoutState as ActivityFeedLayoutState; VirtualizingLayoutContext virtualContext = context as VirtualizingLayoutContext; int currentIndex = state.FirstRealizedIndex; foreach(Rect arrangeRect in state.LayoutRectList) { UIElement containerElement = virtualContext.GetOrCreateElementAt(currentIndex); containerElement.Arrange(arrangeRect); currentIndex++; } return finalSize; } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 행을 위한 레이아웃 경계 사각형 배열 계산하기 - CalculateLayoutBoundRectangleArrayForRow(rowIndex, desiredItemWidth) /// <summary> /// 행을 위한 레이아웃 경계 사각형 배열 계산하기 /// </summary> /// <param name="rowIndex">행 인덱스</param> /// <param name="desiredItemWidth">희망 항목 너비</param> /// <returns>레이아웃 경계 사각형 배열</returns> private Rect[] CalculateLayoutBoundRectangleArrayForRow(int rowIndex, double desiredItemWidth) { Rect[] boundRectangeArrayForRow = new Rect[3]; double yoffset = rowIndex * (MinimumItemSize.Height + RowSpacing); boundRectangeArrayForRow[0].Y = boundRectangeArrayForRow[1].Y = boundRectangeArrayForRow[2].Y = yoffset; boundRectangeArrayForRow[0].Height = boundRectangeArrayForRow[1].Height = boundRectangeArrayForRow[2].Height = MinimumItemSize.Height; if(rowIndex % 2 == 0) { boundRectangeArrayForRow[0].X = 0; boundRectangeArrayForRow[0].Width = desiredItemWidth; boundRectangeArrayForRow[1].X = boundRectangeArrayForRow[0].Right + ColumnSpacing; boundRectangeArrayForRow[1].Width = desiredItemWidth; boundRectangeArrayForRow[2].X = boundRectangeArrayForRow[1].Right + ColumnSpacing; boundRectangeArrayForRow[2].Width = desiredItemWidth * 2 + ColumnSpacing; } else { boundRectangeArrayForRow[0].X = 0; boundRectangeArrayForRow[0].Width = (desiredItemWidth * 2 + ColumnSpacing); boundRectangeArrayForRow[1].X = boundRectangeArrayForRow[0].Right + ColumnSpacing; boundRectangeArrayForRow[1].Width = desiredItemWidth; boundRectangeArrayForRow[2].X = boundRectangeArrayForRow[1].Right + ColumnSpacing; boundRectangeArrayForRow[2].Width = desiredItemWidth; } return boundRectangeArrayForRow; } #endregion } } |
▶ CustomDataTemplateSelector.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; namespace TestProject { /// <summary> /// 커스텀 데이터 템플리트 선택자 /// </summary> public class CustomDataTemplateSelector : DataTemplateSelector { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 일반 템플리트 - NormalTemplate /// <summary> /// 일반 템플리트 /// </summary> public DataTemplate NormalTemplate { get; set; } #endregion #region 강조 템플리트 - AccentTemplate /// <summary> /// 강조 템플리트 /// </summary> public DataTemplate AccentTemplate { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 템플리트 선택하기 (코어) - SelectTemplateCore(item) /// <summary> /// 템플리트 선택하기 (코어) /// </summary> /// <param name="item">항목</param> /// <returns>템플리트</returns> protected override DataTemplate SelectTemplateCore(object item) { if((int)item % 2 == 0) { return NormalTemplate; } else { return AccentTemplate; } } #endregion } } |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
<?xml version="1.0" encoding="utf-8"?> <Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:TestProject" Title="TestProject"> <Grid Name="grid" Margin="10"> <Grid.Resources> <DataTemplate x:Key="NormalItemDataTemplateKey" x:DataType="x:Int32"> <Border Background="{ThemeResource SystemControlBackgroundChromeMediumBrush}"> <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{x:Bind}" /> </Border> </DataTemplate> <DataTemplate x:Key="AccentItemDataTemplateKey" x:DataType="x:Int32"> <Border Background="{ThemeResource SystemControlBackgroundAccentBrush}"> <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="{ThemeResource SystemControlForegroundChromeWhiteBrush}" Text="{x:Bind}" /> </Border> </DataTemplate> <local:CustomDataTemplateSelector x:Key="CustomDataTemplateSelectorKey" NormalTemplate="{StaticResource NormalItemDataTemplateKey}" AccentTemplate="{StaticResource AccentItemDataTemplateKey}" /> <local:ActivityFeedLayout x:Key="ActivityFeedLayoutKey" RowSpacing="10" ColumnSpacing="10" MinimumItemSize="80 110" /> <UniformGridLayout x:Key="UniformGridLayoutKey" MinItemWidth="110" MinItemHeight="110" MinRowSpacing="10" MinColumnSpacing="10" /> </Grid.Resources> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="10" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Border Grid.Column="0" BorderThickness="1" BorderBrush="Black"> <ScrollViewer Name="scrollViewer" Margin="10" IsVerticalScrollChainingEnabled="False"> <ItemsRepeater Name="repeater" ItemTemplate="{StaticResource CustomDataTemplateSelectorKey}" Layout="{StaticResource ActivityFeedLayoutKey}" HorizontalAlignment="Stretch" /> </ScrollViewer> </Border> <StackPanel Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center" Spacing="10"> <RadioButton Name="uniformGridRadioButton" Tag="UniformGridLayoutKey" Content="Uniform grid" /> <RadioButton Name="customVirtualizingLayoutRadioButton" Tag="ActivityFeedLayoutKey" Content="Custom virtualizing layout" IsChecked="True" /> </StackPanel> </Grid> </Window> |
▶ MainWindow.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
using System.Linq; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; namespace TestProject { /// <summary> /// 메인 윈도우 /// </summary> public sealed partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { InitializeComponent(); this.repeater.ItemsSource = Enumerable.Range(0, 500); this.uniformGridRadioButton.Click += layoutRadioButton_Click; this.customVirtualizingLayoutRadioButton.Click += layoutRadioButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 레이아웃 라디오 버튼 클릭시 처리하기 - layoutRadioButton_Click(sender, e) /// <summary> /// 레이아웃 라디오 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void layoutRadioButton_Click(object sender, RoutedEventArgs e) { string layoutKey = ((FrameworkElement)sender).Tag as string; this.repeater.Layout = this.grid.Resources[layoutKey] as VirtualizingLayout; } #endregion } } |