First, if you purely want to use the same DataTemplate
that uses x:Bind
across different components, you don't have to wrap all your elements in either a UserControl or Custom Control.
You just need to create a resource dictionary called Templates.xaml
that includes all the data templates (with x:Bind
!) you want to share, as well as a cs
class with the same name like this -
public partial class Templates
{
public Templates()
{
InitializeComponent();
}
}
Then in your Templates
resource dictionary, add a x:Class
attribute to point to the class you just created -
<ResourceDictionary x:Class="xxx.Templates" ..>
Finally you will need to merge this resource dictionary into your App.xaml
or a parent resource dictionary -
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Fonts.xaml" />
<ResourceDictionary Source="Brushes.xaml" />
<ResourceDictionary Source="Styles.xaml" />
<local:Templates />
</ResourceDictionary.MergedDictionaries>
Now build and run and it should work. Please refer to Igor's excellent post on this topic that I followed a couple of years ago which has worked for me flawlessly. I was even able to create code-behind stuff in there too.
Now back to your original question, would using a UserControl
be bad for performance?
I personally believe the answer is NO in UWP.
Historically in WPF, using a UserControl inside a virtualized items control calls the InitializeComponent()
inside the UserControl
every time a new data template is created, which leads to performance issues so people tend to use a Custom Control instead.
However, this is no longer the case in UWP, where no matter it's a UserControl, Custom Control or even just a Grid
, as long as they have the same exact child elements, they will be loaded the same amount of times. This means that the InitializeComponent
inside the UserControl will only be called a small number of times until the virtualized ListView
has enough numbers to recycle through the whole list.
But keep in mind that another control wrapper is an additional layer, it will always suck a little bit more memory. So unless you want additional logic on your template such as having dependency properties to show/hide stuff, you don't have to extract its content to put into another UserControl or Custom Control.
I hope my explanation makes sense.