1

How can I select all Rectangle, Label, or Button, etc. elements in WPF for applying a property or setting a new resource for these elements from a code behind? Is this possible?

For example:

allRectangleElements.Resources = (ResourceDictionary)FindResource("BlueBrushRect");
Robert Gowland
  • 7,677
  • 6
  • 40
  • 58

1 Answers1

1

You can iterate over all your Rectangle elements using the FindVisualChildren method from this answer:

ResourceDictionary resourceDictionary = (ResourceDictionary)FindResource("BlueBrushRect");

foreach (Rectangle rectangle in FindVisualChildren<Rectangle>(this))
{
    rectangle.Resources = resourceDictionary;
}

Where "this" is my Window object.

But if you want to simply reuse the same ResourceDictionary/Setters over all your Rectangle elements, I would suggest using implicit styles:

<Window.Resources>
    <Style TargetType="Rectangle">
        <Style.Resources>
            <ResourceDictionary ... />
        </Style.Resources>
        <Style.Setters>
            <Setter ... />
            <Setter ... />
        </Style.Setters>
    </Style>
</Window.Resources>
Community
  • 1
  • 1
Raúl Nuño
  • 313
  • 2
  • 12