Selecting user control based on type of DataContext
I'm trying to build a set of typical CRUD maintenance forms in WPF - that are going to be pretty much the same except that they work on different database records.
Rather than creating a new window class for each, I'm trying to use a single window class that instantiated with a different ViewModel class for each database table, and for which I have a different UserControl defined for each ViewModel.
So, if I instantiate the window with its DataContext set to an instance of Record1ViewModel, I want to display it in the window using a Record1UserControl, if it's set to an instance of Record2ViewModel, I want to display it using a Record2UserControl.
I've verified that both user controls work fine, by defining them each directly in the window's XAML. But I've not figured out how to select one or the other, based on the type of the ViewModel.
This is not working:
<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 the ContentPresenter, is the name of the type. The DataTemplates are not used.
Any ideas?
您可以使用DataTemplateSelector为动态选择DataTemplate
在运行时的东西沿着线
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;
}
}
链接地址: http://www.djcxy.com/p/56916.html