Select a user control based on the DataContext type

I am trying to create a set of typical CRUD support forms in WPF - they will be almost the same, except that they work with different database entries.

Instead of creating a new window class for each, I am trying to use one window class that is created with a different ViewModel class for each database table and for which I have a different UserControl defined for each ViewModel model.

So, if I create an instance of a window with its DataContext set to an instance of Record1ViewModel, I want to display it in a window using Record1UserControl, if it is set to an instance of Record2ViewModel, I want to display it using Record2UserControl.

I checked that both user controls work fine, defining them each directly in the XAML window. But I did not understand how to choose one or the other, depending on the type of ViewModel.

This does not work:

<myWindow.Resources> <DataTemplate x:Key="{x:Type ViewModels:Record1ViewModel}"> <MaintenanceControls:Record1 /> </DataTemplate> <DataTemplate x:Key="{x:Type ViewModels:Record2ViewModel}"> <MaintenanceControls:Record1 /> </DataTemplate> </myWindow.Resources> <ContentPresenter Content="{Binding}" /> 

What I get in ContentPresenter is the type name. DataTemplates are not used.

Any ideas?

+7
source share
1 answer

You can use a DataTemplateSelector to dynamically select a DataTemplate while doing something along the lines of

 public class TaskListDataTemplateSelector : DataTemplateSelector { public override DataTemplate SelectTemplate(object item, DependencyObject container) { FrameworkElement element = container as FrameworkElement; if (element != null && item != null && item is Task) { Task taskitem = item as Task; if (taskitem.Priority == 1) return element.FindResource("importantTaskTemplate") as DataTemplate; else return element.FindResource("myTaskTemplate") as DataTemplate; } return null; } } 
+4
source

All Articles