Hello devz,

Let’s say that you want to create your UI but in a dynamic way. Let me explain. Imagine a view which is based on a list of items you want to display. But this list can vary (depending on rights, or context). In this simple example, we want a label with a textbox, then a checkbox. We can do that with a DataTemplateSelector .

This is the final result; a simple list of settings with name and value.

WPF DataTemplateSelector - final result

WPF DataTemplateSelector – final result

First we need a model;

As you can see, there is a field named Type. This enum will determine which template we want to choose in the DataTemplateSelector

Now we can create the SettingTemplateSelector, a class inheriting from DataTemplateSelector. This class allows you to define two templates in your XAML StringTemplate (textbox) and BooleanTemplate (checkbox).

You only need to declare in the ViewModel a list of settings and to initialize it.

Finally, we can use an ItemsControl binded to the list of settings to display. By setting the ItemTemplateSelector to our custom one, the correct template (BooleanTemplate or StringTemplate) will be selected automatically.

Happy coding!  🙂