Posted on January 25, 2012 by Matthieu MEZIL

01/26/2012: Code update

Imagine the following scenario: you have a WCF service with two methods:

  1. List<Customer> GetCustomers();
  2. List<Order> GetOrders(int CustomerId);

You want a treeview with lazy loading in a WPF Window.

There is many way to do it.

I identify three main in my searches:

  • you can use event on your treeview implemented in code-behind

  • you can makes your TreeView control inheriting the framework one’s
  • you can use all the logic on ViewModels and use binding

The last point is realized by adding a CustomerViewModel, having a collection of CustomerViewModel in the VM that encapsulated a Customer and adding IsExpanded property and add the logic of loading orders.

It’s a way often saw in the web and that seems a good way with MVVM for many developers but I think, IMHO, it is NOT a good way.

Indeed, what happens if under Orders, I want OrderDetails? You will add a new OrderViewModel class that encapsulates an Order and the CustomerViewModel class will have a collection of OrderViewModel?

I don’t want to make again my Model in my ViewModel.

I could use the ICustomTypeDescriptor (ICustomTypeProvider in SL) as I did here but I think that if this solution is interesting to add business logic on entity, it is not to add control logic.

I think that the lazy loading control logic should be encapsulated in a behavior and the ViewModel should just have the lazy loading WCF calls logic.

So, I use an ILazyLoader interface:

  1. public interface ILazyLoader
  1. {

string GetChildPropertyName(object obj);

  1. bool IsLoaded(object obj);
  1.     void Load(object obj);

}

and an implementation of it using delegate:

  1. public class LazyLoader : ILazyLoader
  1. {
  1.     private Func<object, string> _getChildPropertyName;
  1.     private Func<object, bool> _isLoaded;
  1.     private Action<object> _load;
  1.     public LazyLoader(Func<object, string> getChildPropertyName, Func<object, bool> isLoaded, Action<object> load)
  1.     {
  1.         _getChildPropertyName = getChildPropertyName;
  1.         _isLoaded = isLoaded;
  1.         _load = load;
  1.     }
  1.     public string GetChildPropertyName(object obj)
  1.     {
  1.         return _getChildPropertyName(obj);
  1.     }
  1.     public bool IsLoaded(object obj)
  1.     {
  1.         return _isLoaded(obj);
  1.     }
  1.     public void Load(object obj)
  1.     {
  1.         _load(obj);
  1.     }

}

Then, in my ViewModel, I use the following code:

  1. public class CustomerViewModel
  1. {
  1.     private ObservableCollection<Customer> _customers;
  1.     public ObservableCollection<Customer> Customers
  1.     {
  1.         get
  1.         {
  1.             if (_customers == null)
  1.             {
  1.                 _customers = new ObservableCollection<Customer>();
  1.                 var customersService = new CustomerServiceClient();
  1.                 EventHandler<GetCustomersCompletedEventArgs> serviceGetCustomersCompleted = null;
  1.                 serviceGetCustomersCompleted = (sender, e) =>
  1.                     {
  1.                         customersService.GetCustomersCompleted -= serviceGetCustomersCompleted;
  1.                         foreach (var ht in e.Result)
  1.                             _customers.Add(ht);
  1.                     };
  1.                 customersService.GetCustomersCompleted += serviceGetCustomersCompleted;
  1.                 customersService.GetCustomersAsync();
  1.             }
  1.             return _customers;
  1.         }
  1.     }
  1.     private ILazyLoader _lazyLoader;
  1.     public ILazyLoader LazyLoader
  1.     {
  1.         get { return _lazyLoader ?? (_lazyLoader = new LazyLoader(obj =>
  1.             {
  1.                 if (obj is HardwareType)
  1.                     return PropertyName.GetPropertyName((Expression<Func<HardwareType, object>>)(ht => ht.Hardwares));
  1.                 return null;
  1.             }, obj => _loadedHardwareTypes.Contains((HardwareType)obj), obj => LoadHardwares((HardwareType)obj))); }

}

  1.     private List<Customer> _loadedCustomers = new List<Customer>();
  1.     private void LoadOrders(Customer c)
  1.     {
  1.         var customerService = new CustomerServiceClient();
  1.         c.Orders.Clear();
  1.         EventHandler<GetOrdersCompletedEventArgs> serviceGetOrdersCompleted = null;
  1.         serviceGetOrdersCompleted = (sender, e) =>
  1.         {
  1.             customerService.GetOrdersCompleted -= serviceGetOrdersCompleted;
  1.             foreach (var o in e.Result)
  1.                 c.Orders.Add(o);
  1.             _loadedCustomers.Add(c);
  1.         };
  1.         customerService.GetOrdersCompleted += serviceGetCustomersCompleted;
  1.         customerService.GetOrdersAsync(c.Id);
  1.     }

}

Now, this is the code of my behavior:

  1. public static class LazyLoadTreeViewItemBehavior
  1. {
  1.     public static ILazyLoader GetLazyLoader(DependencyObject obj)
  1.     {
  1.         return (ILazyLoader)obj.GetValue(LazyLoaderProperty);
  1.     }
  1.     public static void SetLazyLoader(DependencyObject obj, ILazyLoader value)
  1.     {
  1.         obj.SetValue(LazyLoaderProperty, value);
  1.     }
  1.     public static readonly DependencyProperty LazyLoaderProperty =
  1.         DependencyProperty.RegisterAttached("LazyLoader", typeof(ILazyLoader), typeof(LazyLoadTreeViewItemBehavior), new PropertyMetadata(ApplyingLazyLoadingLogic));
  1.     private static void ApplyingLazyLoadingLogic(DependencyObject o, DependencyPropertyChangedEventArgs e)
  1.     {
  1.         var tvi = o as TreeViewItem;
  1.         if (tvi == null)
  1.             throw new InvalidOperationException();
  1.         ILazyLoader lazyLoader= GetLazyLoader(o);
  1.         PropertyInfo childrenProp;
  1.         if (lazyLoader == null)
  1.             return;
  1.         object itemValue = tvi.DataContext;
  1.         string childrenPropName = lazyLoader.GetChildPropertyName(itemValue);
  1.         if (childrenPropName == null || (childrenProp = itemValue.GetType().GetProperty(childrenPropName)) == null)
  1.             return;
  1.         IEnumerable children = (IEnumerable)childrenProp.GetValue(itemValue, null);
  1.         RoutedEventHandler tviExpanded = null;
  1. RoutedEventHandler tviUnloaded = null;
  1.         tviExpanded = (sender, e2) =>
  1.             {
  1.                 tvi.Expanded -= tviExpanded;
  1. tvi.Unloaded -= tviUnloaded;
    if (!lazyLoader.IsLoaded(itemValue))
  1.                 {
  1.                     lazyLoader.Load(itemValue);
  1.                     tvi.Items.Clear();
  1.                     tvi.ItemsSource = children;
  1.                 }
  1.             };
  1.         tviUnloaded = (sender, e2) =>
  1.             {
  1.                 tvi.Expanded -= tviExpanded;
  1.                 tvi.Unloaded -= tviUnloaded;
  1.             };
  1.         if (!children.GetEnumerator().MoveNext())
  1.         {
  1.             tvi.ItemsSource = null;
  1.             tvi.Items.Add(new TreeViewItem());
  1.         }
  1.         tvi.Expanded += tviExpanded;
  1.         tvi.Unloaded += tviUnloaded;

}
}

The thing very interesting with it is the fact that my behavior is not dependent of my model or my ViewModel and can be used with other lazy loading TreeViews.

To do it, I just have to apply our behavior into our TreeView, what can be done in xaml:

  1. <TreeView ItemsSource="{Binding Customers}">
  1.     <TreeView.ItemContainerStyle>
  1.         <Style TargetType="{x:Type TreeViewItem}">
  1.             <Setter Property="local:LazyLoadTreeViewItemBehavior.LazyLoader"
  1. Value="{Binding DataContext.LazyLoader, RelativeSource={RelativeSource AncestorType=local:CustomersWindow}}" />
  1.         </Style>
  1.     </TreeView.ItemContainerStyle>
  1.     <TreeView.ItemTemplate>
  1.         <HierarchicalDataTemplate>
  1.             <HierarchicalDataTemplate.ItemTemplate>
  1.                 <DataTemplate>
  1.                    
  1.                 </DataTemplate>
  1.             </HierarchicalDataTemplate.ItemTemplate>
  1.            
  1.         </HierarchicalDataTemplate>
  1.     </TreeView.ItemTemplate>

</TreeView>

I really like this way. What do you think about it?

Of course, I write my sample with WPF but it’s still true with SL.

Hope this helps…

This entry was posted in 13461, 7671, 8708. Bookmark the permalink.

WPF/SL: lazy loading TreeView的更多相关文章

  1. Angular2+typescript+webpack2(支持aot, tree shaking, lazy loading)

    概述 Angular2官方推荐的应该是使用systemjs加载, 但是当我使用到它的tree shaking的时候,发现如果使用systemjs+rollup,只能打包成一个文件,然后lazy loa ...

  2. Lazyr.js – 延迟加载图片(Lazy Loading)

    Lazyr.js 是一个小的.快速的.现代的.相互间无依赖的图片延迟加载库.通过延迟加载图片,让图片出现在(或接近))视窗才加载来提高页面打开速度.这个库通过保持最少选项并最大化速度. 在线演示    ...

  3. Can you explain Lazy Loading?

    Introduction Lazy loading is a concept where we delay the loading of the object until the point wher ...

  4. [AngularJS] Lazy Loading modules with ui-router and ocLazyLoad

    We've looked at lazy loading with ocLazyLoad previously, but what if we are using ui-router and want ...

  5. [AngularJS] Lazy loading Angular modules with ocLazyLoad

    With the ocLazyLoad you can load AngularJS modules on demand. This is very handy for runtime loading ...

  6. iOS swift lazy loading

    Why bother lazy loading and purging pages, you ask? Well, in this example, it won't matter too much ...

  7. Entity Framework加载相关实体——延迟加载Lazy Loading、贪婪加载Eager Loading、显示加载Explicit Loading

    Entity Framework提供了三种加载相关实体的方法:Lazy Loading,Eager Loading和Explicit Loading.首先我们先来看一下MSDN对三种加载实体方法的定义 ...

  8. Lazy Loading | Explicit Loading | Eager Loading in EntityFramework and EntityFramework.Core

    EntityFramework Eagerly Loading Eager loading is the process whereby a query for one type of entity ...

  9. EFCore Lazy Loading + Inheritance = 干净的数据表 (二) 【献给处女座的DB First程序猿】

    前言 本篇是上一篇EFCore Lazy Loading + Inheritance = 干净的数据表 (一) [献给处女座的DB First程序猿] 前菜 的续篇.这一篇才是真的为处女座的DB Fi ...

随机推荐

  1. mybatis 多数据源

    <environments default="development"> <environment id="development"> ...

  2. 【Unity】12.3 Off Mesh Link组件

    开发环境:Win10.Unity5.3.4.C#.VS2015 创建日期:2016-05-09 一.简介 Off Mesh Link组件用于手动指定路线来生成分离的网格连接.例如,游戏中让行进对象上下 ...

  3. 菜鸟学Java(二十)——你知道long和Long有什么区别吗?

    Java中数据类型分两种: 1.基本类型:long,int,byte,float,double 2.对象类型:Long,Integer,Byte,Float,Double其它一切java提供的,或者你 ...

  4. [Windows Azure] Adding Sign-On to Your Web Application Using Windows Azure AD

    Adding Sign-On to Your Web Application Using Windows Azure AD 14 out of 19 rated this helpful - Rate ...

  5. Asp.Net MVC App_Code无法识别

    Asp.Net MVC需要写公共类的时候 右击添加 App_Code 文件夹,新建类—>右击类—>属性,生成操作 —>选择 —>编译 Asp.Net MVC项目本身是个应用程序 ...

  6. 【转】一件有趣的事:我用 Python 爬了爬自己的微信朋友

    偶然了解到 Python 里的 itchat 包,它已经完成了 wechat 的个人账号 API 接口,使爬取个人微信信息更加方便. 于是乎玩心一起,打算爬一下自己的微信. 步骤核心: 网页启动not ...

  7. 九章面试题:Find first K frequency numbers 解题报告

    Find first K frequency numbers /* * Input: int[] A = {1, 1, 2, 3, 4, 5, 2}; k = 3 * return the highe ...

  8. PHP中的WebService

    Web Service技术, 能使得运行在不同机器上的不同应用无须借助附加的.专门的第三方软件或硬件, 就可相互交换数据或集成.依据Web Service规范实施的应用之间, 无论它们所使用的语言. ...

  9. HTML 学习笔记一

    一.学习HTML有什么用? 可以写网页,也就是网站上的一个页面. 二.HTML 代码是写给谁看的? HTML代码是给浏览器看的,当然,强大的人类也能看得懂,如果你觉得不累的话. 三.HTML的结构 & ...

  10. scala工程导入报错:scalatest_2.10-1.9.1.jar is cross-compiled with an incompatible version of Scala (2.10).

    错误原因: The Scala IDE tries to check if binary incompatible Scala libraries have been inadvertently mi ...