20. May 2022 · Categories: .NET

Windows .NET WPF orders their controls in a visual tree, and this tree has the restraint that every element can only have one parent. This can trip you when define a control as a resource, and then reuse it from the item template of a container. You will see the control exactly once in the list. So never do this in your XAML:

Instead either use templates, with DataTemplate or ControlTemplate, or define a VisualBrush for reuse. The better performance for icons and similar uses is with a visual brush, as it is one item that can be reused and is optimized for painting. For example:

The alternative with ControlTemplate initiates more, but is more compact to describe:

I ran into these problems when I naively tried to use the Visual Studio Image Library for some basic icons for my app. All of their icons are defined as a Rectangle, so these techniques are useful if you want to use them inside of lists.