English 中文(简体)
如何创建将类型存储在类型变量中的类别实例?
原标题:How to create an instance of a class which has its type stored in a Type variable?
  • 时间:2012-05-25 13:58:23
  •  标签:
  • c#
  • wpf

为了尽可能使 WPF 用户控制尽可能通用, 我烦恼了使 WPF 用户控制尽可能通用。 我定义了一个所有用户控制都可以从中产生的基级。 我希望能够通过为用户控制指定 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 Im 的用户控制。

    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> () 设定的类型参数进行用户控制?

我能否创建一个例子, 将这种类型储存在 公共虚拟类型面板Type { get; public set; /code> 中?

如果是的话,如何做到呢?

问题回答

< a href=>""http://msdn.microsoft.com/en-us/library/wccyzw83.aspx" rel=“nofollow” >activator.CreateInstance(类型)





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...