! 제품 버전을 정확하게 입력해 주세요.
제품 버전이 정확하게 기재되어 있지 않은 경우,
최신 버전을 기준으로 안내 드리므로
더욱 빠르고 명확한 안내를 위해
제품 버전을 정확하게 입력해 주세요!

WPF TreeView 요소를 위한 지연 로드(Lazy Loading)를 구현하는 방법 > 블로그 & Tips

본문 바로가기

ComponentOne

블로그 & Tips

WPF TreeView 요소를 위한 지연 로드(Lazy Loading)를 구현하는 방법

페이지 정보

작성자 GrapeCity 작성일 2022-03-08 11:35 조회 2,382회 댓글 0건

본문

첨부파일

WPF TreeView에서 대용량의 데이터를 로딩하려면 시간과 리소스가 많이 소요될 수 있습니다. 그러나 지연 로드와 같이 간단한 요령으로 더 적은 리소스를 사용하면서 데이터를 빠르게 로드할 수 있습니다.

지연 로드를 사용하도록 WPF TreeView를 쉽게 사용자 정의하여 요청이 있을 때 자식 노드를 로드할 수 있습니다. 부모 노드가 확장되면 서비스, 데이터베이스 등에서 자식 노드를 로드할 수 있습니다.

예를 들어, 응용 프로그램이 여러 범주의 제품을 로드하는 경우, 개수가 많으면 모든 제품 및 범주를 로드하는 데 많은 시간이 소요될 것입니다. 그런 경우 자식 노드를 로드하는 최선의 방법은 부모 노드가 확장되었을 때 지연 로드를 수행하는 것입니다.

이 문서에서는 다양한 플랫폼에 사용할 수 있는 ComponentOne 컨트롤 로드 사용 사례와 함께 ComponentOne의 WPF TreeView로 단 두 단계에 걸쳐 지연 로드를 수행합니다.

  1. TreeView 만들기

  2. TreeViewItems에 대한 요청 시 로드 구현


TreeView 만들기

이 단계에서 ComponentOne이 지원하는 플랫폼과 함께 로드되는 TreeView를 만들겠습니다. 다음과 같이 XAML 내에서 C1TreeView 인스턴스를 만드는 것으로 시작하겠습니다.

<c1:C1TreeView x:Name="treeView"
                      Margin="5"
                      SelectionMode="Single"
                      IsVirtualizing="True"
                      SnapsToDevicePixels="True"
                      HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
          <c1:C1TreeView.ItemTemplate>
              <DataTemplate>
                  <Grid Height="40">
                      <TextBlock Text="{Binding Name}"
                                  Margin="8"
                                  HorizontalAlignment="Left"
                                  VerticalAlignment="Center"
                                  Grid.Column="1"
                                  FontFamily="Segoe UI"/>
                  </Grid>
              </DataTemplate>
          </c1:C1TreeView.ItemTemplate>
</c1:C1TreeView>


이제는 모든 플랫폼(부모 노드)을 포함하게 될 루트 노드를 추가하여 TreeView를 초기화할 것입니다.

private void LoadData()
{
    _viewModel.LoadData();
    // Gets the platforms supported by ComponentOne
    var platforms = _viewModel.GetPlatforms();
    treeView.Items.Clear();
​
    // Creating root node
    var rootNode = new C1TreeViewItem()
    {
          IsExpanded = true,
          FontSize = 16
    };
​
    treeView.Items.Add(rootNode);
​
    foreach (var platform in platforms)
    {
          // Adding platforms to root node
          rootNode.Items.Add(CreatePlatformNode(platform));
    }
}


위 코드에서, CreatePlatformNode 메서드를 사용하여 부모 노드를 만들고 추가하는 것을 확인할 수 있습니다. 이에 대해서는 다음 단계에서 간단히 설명하겠습니다. 간단히 말해서 이 메서드는 확장되었을 때 자식 노드를 로드하도록 플랫폼 노드를 구성합니다.



TreeViewItems에 대한 요청 시 로드(On-Demand Load) 구현

이제 TreeView를 준비하여 ComponentOne 플랫폼과 함께 로드했습니다. 이 단계에서는 플랫폼 노드가 확장되었을 때 컨트롤을 로드하기 위해 TreeView로 지연 로드를 수행하겠습니다.


지연 로드 Provider 만들기

다음과 같이 C1TreeViewItems가 요구 시 자식 노드를 로드할 수 있도록 할 Provider를 만드는 것으로 시작하겠습니다.

public abstract class C1TreeViewLazyLoadProvider
{
      ...
      public void LoadOnDemand(C1TreeViewItem parent, object data)
      {
          // Add a dummy node so this node can be expanded
          parent.Items.Add(new C1TreeViewItem());
          /// Hook up event handler for lazy loading support.
          parent.Expanding += OnParentNodeExpanding;
          /// Stores the information to be used for lazy loading.
          _lazyLoadInfo[parent] = data;
      }
​
      private async void OnParentNodeExpanding(object? sender, SourcedEventArgs e)
      {
          var parent = sender as C1TreeViewItem;
          /// Unhook event handler after items are loaded.
          parent.Expanding -= OnParentNodeExpanding;
          await OnRequestingData(parent, _lazyLoadInfo[parent]);
      }
​
      protected abstract Task OnRequestingData(C1TreeViewItem parent, object data);
}


위 코드에서, 자식이 한 번만 로드되도록 핸들러(OnParentNodeExpanding)가 호출되었을 때 LoadOnDemand 메서드 내에 C1TreeViewItem의 (부모) 확장(Expanding) 이벤트를 등록하고 등록을 취소하는 것을 확인할 수 있습니다. 요구 사항에 따라 수정할 수 있습니다.

OnRequestingData라는 추상 메서드가 있는 것도 확인할 수 있습니다. 이 메서드는 C1TreeViewItem이 확장되었을 때 호출되며, 자식 항목을 로드하기 위한 로직을 포함하게 됩니다.

위의 C1TreeViewLazyLoadProvider를 사용하여 아래와 같이 플랫폼 컨트롤에 대한 지연 로드를 구현합니다.

public class ControlsLazyLoader : C1TreeViewLazyLoadProvider
{
    ...
    protected override async Task OnRequestingData(C1TreeViewItem parent, object data)
    {
          _loadIndicator.Visibility = Visibility.Visible;
          var platformId = (string)data;
          await Task.Delay(1000); // Simulate Delay
          // Gets the data from data source
          var controls = await _viewModel.GetControls(platformId);
          // Remove any dummy item
          parent.Items.Clear();
          // Set controls collection as ItemsSource
          parent.ItemsSource = controls;
          parent.Foreground = Brushes.Black;
          _loadIndicator.Visibility = Visibility.Collapsed;
    }
}



TreeViewItems에 대한 지연 로드 구성

마지막으로 자식 노드의 지연 로드를 지원하기 위한 부모 노드를 구성하겠습니다. 첫 단계에서 설명한 CreatePlatformNode 메서드가 여기서 등장하므로 기억해 두시기 바랍니다. CreatePlatformNode 메서드는 이와 같이 이전 단계에서 구현한 ControlsLazyLoader를 사용하여 부모 항목에 대한 지연 로드를 활성화합니다.

private C1TreeViewItem CreatePlatformNode(Platform platform)
{
      var node = new C1TreeViewItem()
      {
            Margin = new Thickness(20, 0, 0, 0),
            IsExpanded = false,
            Foreground = Brushes.Gray
      };
​
      node.Header = new TextBlock() { Text = platform.Name, Padding = new Thickness(10) };
      // setting item template for children
      node.ItemTemplate = treeView.ItemTemplate;
      // Loads children on demand
      _controlsLoader.LoadOnDemand(node, platform.Id);
      return node;
}


이제 다 끝났습니다! WPF C1TreeView에 대한 지연 로드 구현이 완료되었습니다.

지연 로드

이 블로그에서는 ComponentOne의 WPF TreeView를 사용하여 지연 로드를 구현해 보았습니다. C1TreeView 기능에 대한 추가 정보를 여기에서 확인할 수도 있습니다.

의견이나 질문이 있다면 언제든 알려주시기 바랍니다.

샘플 다운로드




지금 바로 ComponentOne을 다운로드하여 직접 테스트해보세요!

 
  • 페이스북으로 공유
  • 트위터로  공유
  • 링크 복사
  • 카카오톡으로 보내기

댓글목록

등록된 댓글이 없습니다.

메시어스 홈페이지를 통해 제품에 대해서 더 자세히 알아 보세요!
홈페이지 바로가기

태그1

메시어스 홈페이지를 통해 제품에 대해서 더 자세히 알아 보세요!
홈페이지 바로가기
이메일 : sales-kor@mescius.com | 전화 : 1670-0583 | 경기도 과천시 과천대로 7길 33, 디테크타워 B동 1107호 메시어스(주) 대표자 : 허경명 | 사업자등록번호 : 123-84-00981 | 통신판매업신고번호 : 2013-경기안양-00331 ⓒ 2024 MESCIUS inc. All rights reserved.