Manipulating WPF Element Tree
Is it possible to programmatically manipulate the WPF control tree?
I have a string that contains arbitrary WPF XAML code. I am displaying content in a content control. No problem yet. Also, I want to decorate each grid control contained in the XAML snippet, and say a custom border.
What are the possible ways to do this?
source to share
You can traverse the control tree and if the current control is of type Grid
add your border to it.
Here's some pseudo code that looks stunningly similar to C # and may actually compile and work:
private void AddGrid(Control c){
foreach(var child in c.Children)
AddGrid(child);
if(this is Grid)
this.Border = new Border(/* whatever */);
}
Alternatively, in the Resources
control that contains your dynamic xaml, you can add Style
one that changes everyone's appearance Grids
and adds the border you want around it. This is a good resource for learning how to do this. Keep in mind that if you add style to window resources or application resources, it will affect all controls in your window or application, respectively. Adding it to the immediate parent of a dynamic xaml will (never tried this before) only affect its child control templates.
source to share