Why using UserControl inside DataTemplate is slower than direct xaml?

妖精的绣舞 提交于 2019-12-06 14:05:25

I know this is an old question, but I ran into this issue recently as well. There is significant overhead in creating user controls in WPF which seems to come from connecting a code-behind class file to the XAML. If all you are trying to do is move XAML to another location, simply define your DataTemplate in a ResourceDictionary in another file, and load it as a StaticResource. This will provide a few advantages:

(1) Ability to use x:Name for elements, which is not allowed in an inline DataTemplate.

(2) Performance. A DataTemplate with direct XAML is orders of magnitude faster than a UserControl in a DataTemplate.

(3) Cleanliness. You can define the DataTemplate wherever you like (a resource dictionary in the same file, near where you're using it, a different file, etc.) and refer to it as a StaticResource.

In my opinion, there is no need to separate the Listbox into a separate UserControl as of now, if you’re using this ListBox only at one place. Anyways if you’re so much concerned about optimizing you code and creating reusable controls, then you can create a separate UserControl. But you cannot have a viewmodel for a reusable usercontrol, since it’s a view based thing.

You have to bind the required properties of the listbox to Dependency Properties and then create the UserControl. By doing so, you’re not violating the MVVM pattern as well as you’re making the control available for others to reuse.

The delay caused is not due to what you did. It’s probably due to data fetching time or some other process causing the application to lag.

You can simplify your "MyViewModelUserControl" - instead of inheriting from UserControl you can inherit directly from Border and do so in its XAML as well (Border instead of UserControl as a root element). That will give you the same performance as you had before, but you can keep it in a separate Control.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!