Well, the problem is that if you have one DataTemplate for an object type, every time an object is present, a DataTemplate will be created that sounds right.
My problem is that our DataTemplate is very heavy and the application can have about 1000 objects using this DataTemplate.
I created a simplified example in which I created 5 Person objects and bind them to a ListView. The DataTemplate for the Person object is a Grid with a label and ContextMenu with 2 MenuItems. For simplicity, I just want to focus on MenuItems. Using the memory profiler, I see that there are only 10 MenuItem objects (2 per person, 5 people * 2 MenuItem = 10 MenuItem), and I want to know if there is a way to avoid this. Let's say each Person object must use the same MenuItem link to avoid duplicating a DataTemplate every time a person is created.
These are the results in the memory profiler.

Thank!
This is my code:
WITH#
using System.Collections.Generic;
using System.Windows;
namespace MenuItemsTest
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
this.DataContext = new List<Person>()
{
new Person("Jim Morrison"),
new Person("Jimmy Page"),
new Person("Jimmy Hendrix"),
new Person("Janis Joplin"),
new Person("Peter Frampton")
};
}
}
public class Person
{
public string Name { get; set; }
public Person(string name)
{
this.Name = name;
}
}
}
XAML:
<Window x:Class="MenuItemsTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MenuItemsTest"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<DataTemplate DataType="{x:Type local:Person}">
<Grid>
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Select" />
<MenuItem Header="Deselect" />
</ContextMenu>
</Grid.ContextMenu>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Content="{Binding Name}" />
</Grid>
</DataTemplate>
</Window.Resources>
<Grid>
<ListView ItemsSource="{Binding}" />
</Grid>
</Window>
Carlo source
share