我不确定我是否正确理解了这个问题,但我认为每种类型的特定 DataTemplates 都是一个想法。
看法 :
<Window x:Class="WpfApplication18.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WpfApplication18="clr-namespace:WpfApplication18"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<DataTemplate DataType="{x:Type WpfApplication18:PersonsVM}">
<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding FirstName}" Header="First name"/>
<DataGridTextColumn Binding="{Binding LastName}" Header="Last name"/>
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
<DataTemplate DataType="{x:Type WpfApplication18:SpecificPersonsVM}">
<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding LastName}" Header="Last name"/>
<DataGridTextColumn Binding="{Binding FirstName}" Header="First name"/>
<DataGridTextColumn Binding="{Binding Age}" Header="Age"/>
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</Grid.Resources>
<ContentControl Content="{Binding}"/>
</Grid>
</Window>
视图模型:
using System.Collections.ObjectModel;
namespace WpfApplication18
{
public class PersonVM
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class SpecificPersonVM : PersonVM
{
public byte Age { get; set; }
}
public class PersonsVM
{
public ObservableCollection<PersonVM> Items { get; private set; }
public PersonsVM()
{
Items = new ObservableCollection<PersonVM>();
}
}
public class SpecificPersonsVM
{
public ObservableCollection<SpecificPersonVM> Items { get; private set; }
public SpecificPersonsVM()
{
Items = new ObservableCollection<SpecificPersonVM>();
}
}
}
安装代码(后面的代码,是的......)
namespace WpfApplication18
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
//SetupPersonsVM();
SetupSpecificPersonsVM();
}
private void SetupSpecificPersonsVM()
{
var vm = new SpecificPersonsVM();
vm.Items.Add(new SpecificPersonVM { FirstName = "Johny", LastName = "Bravo", Age = 17 });
vm.Items.Add(new SpecificPersonVM { FirstName = "Dude", LastName = "Gray", Age = 22 });
vm.Items.Add(new SpecificPersonVM { FirstName = "Scott", LastName = "Thomas", Age = 34 });
DataContext = vm;
}
private void SetupPersonsVM()
{
var vm = new PersonsVM();
vm.Items.Add(new PersonVM { FirstName = "John", LastName = "Scott" });
vm.Items.Add(new PersonVM { FirstName = "Matthew", LastName = "Johnson" });
DataContext = vm;
}
}
}
您可以为不同的虚拟机提供视图服务,它会基于此呈现不同的东西。在我的示例中,两种 VM 类型都有一个 DataGrid,但它可能更加不同。