Page 1 of 1

Load and parse component xaml only once?

Posted: 26 May 2022, 08:56
by MarkSim
I have a view where many component items (UserControls) are displayed using an ItemsControl. The DataTemplate references a UserControl I define in another xaml file. I'm finding that for every single item, it wants to reload the xaml over and over, which I assume also means parsing it over and over which is quite expensive. Is there a way to load and parse it just once other than copying the xaml into the main view?

Only thing I can think of right now is definining it in a resource file instead somehow.. Is that the best way?

Re: Load and parse component xaml only once?

Posted: 26 May 2022, 13:43
by sfernandez
Hi, this is something that has been asked a few times and we have plans to address this problem: #1301. The idea is storing in a cache the internal parsing of the XAML, then each time a new UserControl is requested we only have to instantiate that internal tree. That should be a lot faster than loading the XAML from the file system and parsing it every time.

In the meantime, does your user control have any code behind? If it is only a xaml encapsulating a bunch of controls then you can define a control template instead:
<Grid ...>
  <Grid.Resources>
    <ControlTemplate x:Key="MyControl" TargetType="Control">
      ...
    </ControlTemplate>
  </Grid.Resources>
  <StackPanel>
    <Control Template="{StaticResource MyControl}"/>
    <Control Template="{StaticResource MyControl}"/>
  </StackPanel>
</Grid>

Re: Load and parse component xaml only once?

Posted: 27 May 2022, 09:59
by MarkSim
Yep that worked, thanks!

Re: Load and parse component xaml only once?

Posted: 06 Jul 2022, 09:41
by decai
Hi,
We also has this situation, but our user control has code behind. How should we optimize it?

Re: Load and parse component xaml only once?

Posted: 06 Jul 2022, 16:58
by sfernandez
We also has this situation, but our user control has code behind. How should we optimize it?
Hi, if you cannot move the UserControl code to a view model, so you can convert it to a simple control template there is not much you can do now.
But loading and parsing a UserControl xaml shouldn't cost a lot, unless it is huge or it is loading lots of other resource dictionary xamls. Is that your case?