Is it possible to use reflection directly in XAML

In my database, I have a table that contains different userControls with the attributes "ClassName", "AssemblyName" and "NameSpace", which are necessary to initialize instances using reflection.

My idea: to collect this collection from the database, set the collection as a data context and dynamically load these user elements into tabcontrol. I could use a "tabItem", which will contain it at runtime in the code for loading. I think it would be very convenient and fantastic if it could be done directly from XAML in the template.

I was looking for something similar, but could not find anything without using the code.

I thought something like the following

<TabControl.ContentTemplate> <DataTemplate> <xxxControl ClassName="{Binding ClassName}" AssemblyName="{Binding AssemblyName}" NameSpace="{Binding NameSpace}" /> </DataTemplate> </TabControl.ContentTemplate> 

I could create such an "xxxControl", but that would be a waste of time if something like that already exists. Thus, the GUI can be fully generated by the parameters in the database.

+4
source share
2 answers

You can do a lot in XAML with markup extensions , in which case you can create one that creates controls from this information. To do this, he needs some dependency properties that can be related, and in ProvideValue he will get the assembly, build the full name and instantiate.

Using:

 <DataTemplate> <me:Instance Assembly="{Binding AssemblyName}" NameSpace="{Binding NameSpace}" Class="{Binding ClassName}"/> </DataTemplate> 

Obviously, you still have the code, but the way it should be, the imperative code does not belong to XAML at all.

Also, I doubt that your database should contain information about user interface controls ...

+1
source

Ugh. Do not control your user interface directly from the database. The closest you should come (provided that you cannot make significant changes to the architecture). IMO will load your database records into the IObservable in your virtual machine and use the DataTemplateSelector to translate the collection into user interface controls.

+1
source

Source: https://habr.com/ru/post/1480943/


All Articles