0
我打算让WPF UserControl尽可能通用。我已经定义了一个基类,所有的用户控件都可以解决这个问题。我希望能够通过为UserControl或甚至基类指定类型参数来使其具有通用性,但这似乎不可能。如何创建类型存储在Type变量中的类的实例?
由于周围的工作,我尝试设置一个类型作为参数,如:
public class UCBase : UserControl
{
public virtual Type UCType { get; private set; }
public virtual Type PanelType { get; private set; }
internal void SetType<TVM, TPanel>() where TPanel : new()
{
UCType = typeof(TVM);
PanelType = typeof(TPanel);
}
}
后来,我需要UCType
表示创建一个实例类,特别是知道如何另一个用户控制来处理ViewModel我要通过它。
public ZonesAccordionPanel(List<ViewModelBase> vmItems)
{
InitializeComponent();
foreach (var item in vmItems)
{
var exp = new Expander { Header = new ZoneReport(item) };
exp.Resources.Add("item", item);
exp.Expanded += exp_Expanded;
accordion.Children.Add(exp);
}
}
void exp_Expanded(object sender, RoutedEventArgs e)
{
var expander = (Expander) sender;
var currentItem = expander.Resources["item"];
// I have my data and I'd like to pass that to a specific UserControl
// that knows how to deal with that data the way I want
}
我怎样才能使基于该类型参数我设置与SetType<TVM, TPanel>()
用户控制?
是否可以创建一个类型为public virtual Type PanelType { get; private set; }
的实例?
如果是这样,怎么样?
你有没有看着Activator.CreateInstance?如果你的'UCType'类型是通用的(换句话说,'UCType'),那么你可以做'Activator.CreateInstance(UCType.MakeGenericType(new [] {PanelType}),)''。 –
SPFiredrake