我有一个样本MVVM WPF应用程序,我在为我的动态加载的模型创建DataTemplates时遇到问题。让我尝试解释一下:
我有以下简化的类作为我的Model的一部分,我正在动态加载:
public class Relationship
{
public string Category { get; set; }
public ParticipantsType Participants { get; set; }
}
public class ParticipantsType
{
public ObservableCollection<ParticipantType> Participant { get; set; }
}
public class ParticipantType
{
}
public class EmployeeParticipant : ParticipantType
{
public EmployeeIdentityType Employee { get; set; }
}
public class DepartmentParticipant : ParticipantType
{
public DepartmentIdentityType Department { get; set; }
}
public class EmployeeIdentityType
{
public string ID { get; set; }
}
public class DepartmentIdentityType
{
public string ID { get; set; }
}
这是我的视图模型,我创建了一个通用对象Model
属性来公开我的模型:
public class MainViewModel : ViewModelBase<MainViewModel>
{
public MainViewModel()
{
SetMockModel();
}
private void SetMockModel()
{
Relationship rel = new Relationship();
rel.Category = "213";
EmployeeParticipant emp = new EmployeeParticipant();
emp.Employee = new EmployeeIdentityType();
emp.Employee.ID = "222";
DepartmentParticipant dep = new DepartmentParticipant();
dep.Department = new DepartmentIdentityType();
dep.Department.ID = "444";
rel.Participants = new ParticipantsType() { Participant = new ObservableCollection<ParticipantType>() };
rel.Participants.Participant.Add(emp);
rel.Participants.Participant.Add(dep);
Model = rel;
}
private object _Model;
public object Model
{
get { return _Model; }
set
{
_Model = value;
NotifyPropertyChanged(m => m.Model);
}
}
}
接着我尝试创建一个ListBox来专门显示“Participants”集合:
<ListBox ItemsSource="{Binding Path=Model.Participants.Participant}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Expander Header="IdentityFields">
<!-- WHAT TO PUT HERE IF PARTICIPANTS HAVE DIFFERENT PROPERTY NAMES -->
</Expander>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
问题是:
1. 我不知道如何创建一个可以处理两种参与者类型的模板,在这种情况下,我可能会有EmployeeParticipant或DepartmentParticipant,因此,根据情况,数据绑定路径将被设置为Employee或Department属性。 2. 我考虑为每种类型创建一个DataTemplate(例如x:Type EmployeeParticipant),但问题在于我的模型类在运行时动态加载,因此VisualStudio会抱怨这些类型不存在于当前解决方案中。
那么如果我的具体类型在编译时未知,只有在运行时才知道,我该如何在ListBox中表示这些数据呢?
编辑:添加了我的测试ViewModel类