0

I have multiple XAML files containing a UserControl (they are SVG images converted to XAML). In C#, to have that image in a Grid for example, I would use a XamlReader and add the root element to the grid's children.

StreamReader sr = new StreamReader("example.xaml");
UIElement rootElement = (UIElement) XamlReader.Load(sr.BaseStream);
theGrid.Children.Add(rootElement);

How can I do the same in XAML (where I would use a path to the image XAML from a binding)?

I am looking for this approach in order to follow the MVVM principle of separating UI from code.

Basa
  • 101
  • 3
  • 9
  • 2
    You may perhaps bind the Content property of a ContentControl, with a Binding Converter that returns the result of XamlReader.Load. – Clemens Jan 09 '18 at 11:45
  • MVVM != no codebehind. UI code is perfectly fine in your codebehind. This is UI code. It's also really weird, and there's probably a better way of accomplishing your goals. –  Jan 09 '18 at 17:24
  • Most obvious approach is to declare the converted XAML as resources and then reference the resource. But, even with more context and a [mcve] there would be many possible ways to approach the problem, and as stated, even more. Your question is way too broad. Try _something_, ask for help if you can't get that _specific_ thing to work. – Peter Duniho Jan 09 '18 at 22:17
  • Thank you, @Clemens. That best answered my issue and was the approach I went with. I'll mark it as the solution should you provide it as an answer. – Basa Feb 23 '18 at 18:18
  • I'm glad I could help. Please note that you can also write (and later accept) an answer to your own question. Just post your solution. – Clemens Feb 23 '18 at 18:39

2 Answers2

1

You may perhaps bind the Content property of a ContentControl, with a Binding Converter that returns the result of XamlReader.Load.

Solution suggested by Clemens.

Basa
  • 101
  • 3
  • 9
0

WPF What is the correct way of using SVG files as icons in WPF

Describes the problem. Bottom line is there are tools to convert SVG to xaml. Google around a bit you Will find plenty of tools. The link also has useful information.

An SVG is An image, i also don't see the link with mvvm. Unless your image is not fixed. Based on your question it appears you want a fixed converted xaml in another xaml.

I think it is a matter of copy-paste the relevant part in your target xaml control.There is a little overhead.

If the image is not fixed, you load a string to fill the path. That would be bindable by mvvm in a viewmodel that loads and assigns a property with inotifypropertychanged.

Philip Stuyck
  • 7,344
  • 3
  • 28
  • 39