tobi_fis
tobi_fis

Reputation: 55

Load .xaml file and edit object tree at runtime

After reading into XamlWriter and XamlReader, I was wondering if it is possible to load an arbitrary .xaml file at runtime, edit the object tree and then reuse it again.

What I am trying to create is a kind of showcase application for all available styles of a project. I've got TemplateViews for several ControlTypes (such as ButtonTemplateView.xaml, ListboxTemplateView.xaml ...), with their Style property bound to a viewmodel, which get dynamically constructed for each fitting style at runtime and then added to the main view. But I also want to show all styles for the CustomControls of the project, which right now I am doing via Activator.CreatInstance with the TargetTypeof the style, and then adding the object to the main view.

Now, lets say if a CustomControl MyCustomTextBox is based on a TextBox, can I just load the TextBoxTemplateView.xaml, switch every <TextBox ... /> to a <MyCustomTextBox .../> and then add it to my main view?
If so, how? Can I turn it into a string and just replace the words and then turn it back into something usable? Or do I have to edit the UserControl object I get when I use XamlReader.Load? Or something else?

I hope this is not a duplicate question (at least I didnt find anything like it) and thanks for any help in advance.

Upvotes: 1

Views: 529

Answers (1)

mm8
mm8

Reputation: 169250

You could either replace all occurances of <TextBox> with <local:MyCustomTextBox> in the string that you pass to the XamlReader.Load method. This is probably the easiest way because then the XamlReader will create the MyCustomTextBox elements for you.

The other option would be to iterate through the <TextBox> elements in the UserControl that is returned from the XamlReader.Load method and replace these by MyCustomTextBox elements. How to do this depends on where the controls are located in the element tree of the UserControl.

Upvotes: 1

Related Questions