我有一个示例MVVM WPF应用程序,并且在为我的动态加载模型创建DataTemplates时遇到问题。让我试着解释一下:动态加载类型的ListBox DataTemplate
我有以下简单的类作为我的模型的一部分,这我加载动态
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 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>
的问题是:
- 我不知道如何创建一个模板,可以处理这两种类型的参与antType,在这种情况下,我可以有EmployeeParticipant或DepartmentParticipant,因此根据它,数据绑定路径将被设置为
Employee
或Department
相应的属性 - 我虽然要为每种类型创建一个DataTemplate(例如, x:类型EmployeeParticipant),但问题是我的模型中的类在运行时动态加载,所以VisualStudio会抱怨这些类型在当前解决方案中不存在。
如何在ListBox中表示这些数据,然后如果我的具体类型在编译时不知道,但只在运行时?
编辑:增加我的测试ViewModel类
这里一个相关的问题http://stackoverflow.com/questions/11152401/explicitly-set-wpf-binding-datatype – 2013-02-12 15:49:16